使用角色注释保护不起作用(Jersey)

时间:2015-12-28 16:28:03

标签: java web-services rest jersey jax-rs

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

现在我正在寻求帮助:我在我的小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());
    }
}

这是我的应用程序类:

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

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

有了这一切,当我请求URI问候语/全部时,一切正常,字符串“Hello,everybody!”显示。但是,当我请求URI greeting / admin时,即使我的isUserInRole方法总是返回true,也不会调用admin管理角色中的用户请求它时调用它。事实上,我的filter方法总是被调用,但我的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问候/管理员时,我顺便得到403 Forbiden(我忘了说)

1 个答案:

答案 0 :(得分:0)

查看RoleAllowedRequestFilter的源代码。对用户进行身份验证时,预计会有关联的Principal。过滤器会检查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;
}

因此,您需要在Principal

getUserPrincipal中返回SecurityContext
@Override
public Principal getUserPrincipal() {
    return new Principal() {
        @Override
        public String getName() {
            return "Some Name";
        }
    };
}
相关问题