dropwizard中的身份验证流程

时间:2018-06-22 12:04:58

标签: java rest authentication dropwizard

我参加了很多论坛来了解流程,但仍然对正确的流程感到困惑。

我正在使用Dropwizard,首先我想从REST API中获取令牌(用户名和密码将在基本身份验证中提供),然后下次将此令牌传递到每个请求中。

主班

    environment.jersey()
                .register(
                        new AuthDynamicFeature(
                                new JwtAuthFilter.Builder<User>()
                                        .setAuthenticator(new MarginCalcAuthenticator())
                                        .setAuthorizer(
                                                new CalcAuthorizer())
                                        .setRealm("BASIC-AUTH-REALM")
                                        .buildAuthFilter()));
environment.jersey().register(RolesAllowedDynamicFeature.class);
        environment.jersey().register(new AuthValueFactoryProvider.Binder<User>(User.class));

AuthFilter

@Priority(Priorities.AUTHENTICATION)
public class JwtAuthFilter<P extends Principal> extends AuthFilter<JWTCredentials, P> {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthFilter.class);
    public static final String AUTHENTICATION_HEADER = "Authorization";

    @Override
    public void filter(final ContainerRequestContext requestContext) throws IOException {
        String authCredentials = requestContext.getHeaderString(AUTHENTICATION_HEADER);

身份验证器

public class CalcAuthenticator implements Authenticator<JWTCredentials, User> {

    public Optional<User> authenticate(JWTCredentials credentials)
            throws AuthenticationException {
        AdminAuthenticationService authService = new AdminAuthenticationService();

        User userObj = authService.authenticate(credentials.getJwtToken());
        if (userObj == null) {
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
        return Optional.of(userObj);
    }

}

REST API资源类

@GET
    @Path("token")
    @Produces(MediaType.TEXT_PLAIN)
    public Response genToken(@Context SecurityContext sc){
        return Response
                .ok()
                .header("Authorization", "Bearer "+AdminAuthenticationService.issueToken((br.dc.auth.User) sc
                        .getUserPrincipal())).build();
    }

我正在从Postman调试,它正在击中我的API genToken,但它从未出现在JwtAuthFilter或CalcAuthenticator中。谁能帮助我了解流程?我想了解流程。

1 个答案:

答案 0 :(得分:0)

正如Paul提到的那样,需要使用@RolesAllowed(或任何其他authz anno)注释的类或方法进行身份验证。 auth仅在您告诉它的方法(或类)上完成。

流量 在环境中注册过滤器,身份验证器等->启动服务器->从UI或邮递员请求令牌->它将命中AuthFilter->您可以致电身份验证器以进行令牌验证->身份验证请求并相应地发送响应。