【发布时间】:2013-06-12 14:47:53
【问题描述】:
我正在尝试使用 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 docRolesAllowedDynamicFeature 之后应该调用这个方法。
如何使用 RolesAllowedDynamicFeature?
【问题讨论】:
标签: java authentication jersey authorization jax-rs