java – 使用ContainerRequestFilter在Jersey WebService中自定义@RolesAllowed角色

我使用ContainerRequestFilter接口创建了一个过滤器,并尝试分配返回用户实体的自定义角色.

 @Override
public ContainerRequest filter(ContainerRequest request) {
    User user = authenticate(request);
    if (user != null) {
        request.setSecurityContext(new Authorizer(user));
    } else {
        throw new WebApplicationException(400);
    }
    return request;

}

 private User authenticate(ContainerRequest request) {

    user = new User("erhan", "customRole");


    return user;
}

public class Authorizer implements SecurityContext {

    private User user;
    private Principal principal;

    public Authorizer(final User user) {
        this.user = user;
        this.principal = new Principal() {

            public String getName() {
                return user.username;
            }
        };
    }

    public Principal getUserPrincipal() {
        return this.principal;
    }

    public boolean isUserInRole(String role) {
        return (role.equals(user.role));
    }

    public boolean isSecure() {
        return "https".equals(uriInfo.getRequestUri().getScheme());
    }

    public String getAuthenticationScheme() {
        return SecurityContext.BASIC_AUTH;
    }
}

public class User {

    public String username;
    public String role;

    public User(String username, String role) {
        this.username = username;
        this.role = role;
    }
}

使用该过滤器一切都很好,但是当它进入Web服务时

 @GET
 @RolesAllowed({"customRole"})
 @Path("/test")
 public String getByType(@Context HttpHeaders headers,@Context SecurityContext sc,
                                 @Context HttpServletRequest request) {



   return null;
 }

它到达webservice但是当我改变角色时,仍然达到了相同的web服务.我如何在泽西岛提供不同的自定义角色?

最佳答案 使用Jersey 2,您只需注册RolesAllowedDynamicFeature并在web.xml中保护您的应用程序.比你不需要自定义SecurityContext实现.

有关详细信息,请参见Jersey custom SecurityContext on EJB jax-rs resource.

点赞