java – 使用RolesAllowedDynamicFeature和Jersey授权

前端之家收集整理的这篇文章主要介绍了java – 使用RolesAllowedDynamicFeature和Jersey授权前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用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?

解决方法

您需要为身份验证过滤器定义优先级,否则RolesAllowedDynamicFeature中的RolesAllowedRequestFilter将在AuthenticationFilter之前执行.如果查看源代码,RolesAllowedRequestFilter具有注释@Priority(Priorities.AUTHORIZATION),因此如果将@Priority(Priorities.AUTHENTICATION)分配给您的身份验证过滤器,它将在RolesAllowedRequestFilter之前执行.像这样:
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

您可能还需要使用寄存器(AuthenticationFilter.class)实际注册AuthenticationFilter,具体取决于您的服务器是否扫描注释.

猜你在找的Java相关文章