我正在尝试使用到目前为止似乎有效的 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
错误,并且isUserInRole
我的 SecurityContext 的方法永远不会被调用。按照API 文档RolesAllowedDynamicFeature 应该调用此方法。
如何使用 RolesAllowedDynamicFeature?