保护角色注释不起作用(泽西岛)

Securing with roles annotations not working (Jersey)

我是新来的,尽管我以前在这里找到了很多问题的答案。

现在我正在寻求帮助:我的小 REST 上有这个小示例资源 API:

@Path("/greeting")
@PermitAll
public class HelloResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("all")
    public String sayHelloToAll() {
        return "Hello, everybody!";
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @RolesAllowed("admin")
    @Path("admin")
    public String sayHelloToAdmin() {
        return "Hello, admin!";
    }
}

为了过滤角色,我有这个 SecurityContext 的实现:

public class Authorizer implements SecurityContext {

    @Override
    public String getAuthenticationScheme() {
        return null;
    }

    @Override
    public Principal getUserPrincipal() {
        return null;
    }

    @Override
    public boolean isSecure() {
        return false;
    }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }
}

ContainerRequestFilter 的这个实现:

@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        requestContext.setSecurityContext(new Authorizer());
    }
}

这是我的申请class:

@ApplicationPath("/")
public class Application extends ResourceConfig {

    public Application() {
        super(HelloResource.class);
        register(AuthorizationFilter.class);
        register(RolesAllowedDynamicFeature.class);        
    }
}

有了这一切,当我请求 URI greeting/all 时,一切正常,显示了字符串 "Hello, everybody!"。但是,当我请求 URI greeting/admin 时,即使我的 isUserInRole 方法始终 returns 为真,也永远不会调用该 URI greeting/admin,当管理员角色的用户请求它时应该调用它。事实上,我的过滤器方法总是被调用,但我的 isUserInRole 方法从未被调用。

我听从了很多建议:

SecurityContext doesn't work with @RolesAllowed

Authorization with RolesAllowedDynamicFeature and Jersey

How to access Jersey resource secured by @RolesAllowed

Best practice for REST token-based authentication with JAX-RS and Jersey

但它似乎对任何东西都不起作用。

谁能帮帮我?我不知道我是否遗漏了什么

提前谢谢大家。

编辑:当我请求 URI greeting/admin 时,我顺便得到了 403 Forbiden(我忘记说了)

查看 RoleAllowedRequestFilter. When a user is authenticated, it is expected that there be an associated Principal. The filter checks it here

的源代码
if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
    throw new ForbiddenException(LocalizationMessages.USER_NOT_AUTHORIZED());
}
...
private static boolean isAuthenticated(final ContainerRequestContext requestContext) {
    return requestContext.getSecurityContext().getUserPrincipal() != null;
}

所以你需要return一个PrincipalgetUserPrincipalSecurityContext

@Override
public Principal getUserPrincipal() {
    return new Principal() {
        @Override
        public String getName() {
            return "Some Name";
        }
    };
}