【问题标题】:Dropwizard authentication header tokenDropwizard 身份验证标头令牌
【发布时间】:2018-01-25 12:15:38
【问题描述】:

我正在尝试在 Dropwizard 网络应用程序中实现 OAuth2 身份验证。我创建了所需的AuthenticatorAuthorizer 类,并在我的应用程序的运行方法中添加了Dropwizard manual 中提供的代码,如下所示:

environment.jersey().register(new AuthDynamicFeature(
                new OAuthCredentialAuthFilter.Builder<User>()
                .setAuthenticator(new TokenAuthenticator(service))
                .setAuthorizer(new TokenAuthorizer())
                .setPrefix("Bearer")
                .buildAuthFilter()));
        environment.jersey().register(RolesAllowedDynamicFeature.class);
        //If you want to use @Auth to inject a custom Principal type into your resource
        environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));

我需要的行为是,在我的客户通过在我的登录页面上提供他/她的凭据登录后,我想将客户重定向到我使用 Dropwizard Views 创建的问候页面,并且位于路径下:“/me "如下:

//After succesfull login and token generation
return Response.seeOther(new URI("/me")).build(); // redirect to greeting page

我的问候资源如下所示:

@Path("/me")
@Produces(MediaType.TEXT_HTML)
public class UserResource {

    @GET
    public UserView getView(@Auth User user) {
            return new UserView(user);
    }

}

目前我收到“访问此资源需要凭据”。登录后响应。在阅读了令牌身份验证 (nice explanation here) 之后,我发现令牌必须从客户端在每个请求的标头中发送。所以我的问题是如何告诉用户的浏览器(客户端)将令牌包含在未来请求的标头中?

【问题讨论】:

  • 感谢关于令牌解释的链接。

标签: authentication login oauth-2.0 dropwizard


【解决方案1】:

我通过以下方式设法解决了这个问题:

为了验证用户,必须在请求的头部以Authorization: Bearer &lt;token-value&gt;的形式发送一个令牌。此令牌由服务器在身份验证时发送,并且必须由客户端/用户存储以在将来的请求中发送。当我提交登录表单时,我设法通过使用 ajax 请求来存储令牌,如下所示:

<#-- Handle form submission response to save the token on the client side-->
<script>
    $('#loginForm').submit(function(event){
        event.preventDefault();
        $.ajax({
          url: $(this).attr('action'),
          type: 'POST',
          data : $(this).serialize(),
          dataType: 'json',
          success: function(data){
            //alert("The server says success!!: " +data);
            console.log(data);
            window.sessionStorage.accessToken = data.token;
            window.location = data.url;

          },
          error: function(data){
            alert("The server says error! : ");
            console.log(data);
          }
        });
});
</script>

然后登录资源生成 JSON,该 JSON 在上述代码中的数据变量中接收。所需的令牌驻留在 data.token 中 - 然后将其存储。我在名为“url”的 JSON 中添加了第二个条目,以指示成功验证后重定向到的路径。

现在令牌在需要时存储在客户端。为了在请求标头中发送此令牌,我需要更改使用 Dropwizard 提供的视图的方法。我没有直接要求身份验证,而是拆分了 View 的资源和经过身份验证的数据资源。为了澄清,请考虑以下示例。用户登录,获取令牌,然后转到显示他/她的用户名的页面。对于页面,使用 .ftl 文件创建视图资源以用作模板。类似的东西:

@Path("/me")
@Produces(MediaType.TEXT_HTML)
public class UserResource {


    @GET
    public UserView getView() {
       return new UserView();

    }
}

还有……

public class UserView extends View {

    public UserView() {
        super("user.ftl");

    }
}

还有user.ftl:

<#include "include/head.html">
<#include "include/header.html">

<!-- Header --> 
<div id ="headerWrapper">
</div>

<div class="container-fluid">

<div id="name">
    <p>Hello user</p>
</div>

</div>

<#include "include/footer.html">

现在为了检索用户名,我创建了一个新资源,它在新路径上生成 JSON。例如:

@Path("/getdetails")
@Produces(MediaType.APPLICATION_JSON)
public class UserDetailsResource {

    @GET
    @Timed
    @UnitOfWork
    public User getDetails(@Auth User user) {

        return user;
    }

}

此资源需要身份验证并提供可以从中检索用户名的 JSON。现在要获取用户名并将其放置在视图中,只需将脚本添加到 users.ftl 并使用对 getdetails 资源的 ajax 请求,在标头中提供令牌并使用结果将用户名放置在视图中。请参阅下面的脚本。

<script>

  $.ajax({
          url: '/getdetails',
          type: 'GET',
          headers: {"Authorization": window.sessionStorage.accessToken},
          dataType: 'json',
          success: function(data){
            //alert("The server says success!!: " +data);
            console.log(data);
            $("#name").text('Hello '+data.username);
          },
          error: function(data){
            alert("The server says error! : ");
            console.log(data);
          }
        });

</script>

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多