SecurityContext不适用于@RolesAllowed

tob*_*pls 7 jax-rs jersey java-ee tomcat7

我目前在Tomcat 7.对于安全使用创建新泽西2.5.1后端服务器我使用的@RolesAllowed,@PermitAll等注释,我创建了我的自定义ContainerRequestFilterSecurityContext.

我的问题是,当我的@RolesAllowed注释资源被请求时,它总是拒绝权限,即使我强制我的isUserInRole(role)方法返回true.但是,我的filter方法被调用.你有什么建议吗?我将在下面粘贴一些相关代码.

我的ContainerRequestFilter实施:

public class AuthorizationFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext request) throws IOException
    {
        request.setSecurityContext(new Authorizer());
    }
}
Run Code Online (Sandbox Code Playgroud)

我的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的资源:

@Path("/secure")
public class TestSecureResource {

    @GET
    @PermitAll
    @Path("/nonsec_test/{text}")
    public Response nonSecureTest(
            @PathParam("text") String text){

        return Response.status(200).entity(text).build();
    }

    @GET
    @RolesAllowed("admin")
    @Path("/sec_test/{text}")
    public Response secureTest(
            @PathParam("text") String text){

        return Response.status(200).entity(text).build();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的ResourceConfig:

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

    public MyApplication() {
        super(TestSecureResource.class);
        register(RolesAllowedDynamicFeature.class);
        register(AuthorizationFilter.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的相关部分web.xml:

<servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>pkg.backend</param-value>
        </init-param>

        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>pkg.backend.MyApplication</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
Run Code Online (Sandbox Code Playgroud)

在这种特定情况下,我的访问权限secureTest始终被拒绝.澄清事情; 我收到HTTP状态码403 - 禁止.

提前谢谢你们

Mic*_*dos 9

确保您已AuthorizationFilter在您的注册中注册MyApplication(请参阅在Jersey 2中注册资源和提供程序)或使用@Provider注释(以便通过程序包扫描使其可被发现).

要使用安全注释(包javax.annotation.security)来限制对资源的访问,您需要注册RolesAllowedDynamicFeature.

编辑1

AuthorizationFilter还必须注释,@PreMatching这意味着在匹配阶段(uri - > resource)之前调用过滤器.否则,RolesAllowedDynamicFeature(在此阶段期间调用)注册的过滤器将不会看到自定义SecurityContext.

编辑2

Jersey用户指南 - 授权 - 保护资源