我正在尝试使用JAX-RS过滤器对用户进行身份验证,到目前为止似乎还行得通。这是我要设置新SecurityContext的过滤器:
@Provider
public class AuthenticationFilter implements ContainerRequestFilter {
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return new Principal() {
@Override
public String getName() {
return "Joe";
}
};
}
@Override
public boolean isUserInRole(String string) {
return false;
}
@Override
public boolean isSecure() {
return requestContext.getSecurityContext().isSecure();
}
@Override
public String getAuthenticationScheme() {
return requestContext.getSecurityContext().getAuthenticationScheme();
}
});
if (!isAuthenticated(requestContext)) {
requestContext.abortWith(
Response.status(Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Example\"")
.entity("Login required.").build());
}
}
private boolean isAuthenticated(final ContainerRequestContext requestContext) {
return requestContext.getHeaderString("authorization") != null; // simplified
}
}
资源方法如下所示:
@GET
// @RolesAllowed("user")
public Viewable get(@Context SecurityContext context) {
System.out.println(context.getUserPrincipal().getName());
System.out.println(context.isUserInRole("user"));
return new Viewable("index");
}
RolesAllowedDynamicFeature的注册方式如下:
.register(RolesAllowedDynamicFeature.class)
我可以在控制台上看到预期的输出。但是,如果取消注释
@RolesAllowed("user")
,则会收到Forbidden
错误,并且不会调用SecurityContext的isUserInRole
方法。在API doc之后,RolesAllowedDynamicFeature应该调用此方法。如何使用RolesAllowedDynamicFeature?
最佳答案
您需要为身份验证过滤器定义优先级,否则RolesAllowedRequestFilter
中的RolesAllowedDynamicFeature
将在AuthenticationFilter
之前执行。如果您查看源代码,则RolesAllowedRequestFilter
具有注释@Priority(Priorities.AUTHORIZATION)
,因此,如果将@Priority(Priorities.AUTHENTICATION)
分配给身份验证过滤器,它将在RolesAllowedRequestFilter
之前执行。像这样:
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
您可能还需要使用
AuthenticationFilter
实际注册register(AuthenticationFilter.class)
,这取决于服务器是否扫描注释。