java-ee – SecurityContext不适用于@RolesAllowed

我目前正在Tomcat 7中使用Jersey 2.5.1创建一个后端服务器.为了安全,我使用了@RolesAllowed,@ PermitAll等注释,我创建了自定义的ContainerRequestFilter和SecurityContext.

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

我的ContainerRequestFilter实现:

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

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

}

我的资源:

@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();
    }
}

我的资源配置:

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

    public MyApplication() {
        super(TestSecureResource.class);
        register(RolesAllowedDynamicFeature.class);
        register(AuthorizationFilter.class);
    }
}

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

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

提前谢谢你们

解决方法

确保您的AuthorizationFilter已在MyApplication中注册(请参阅 Registering Resources and Providers in Jersey 2)或使用 @Provider注释(以使其可通过包扫描发现).

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

编辑1

您的AuthorizationFilter也必须使用@PreMatching进行注释,这意味着在匹配阶段(uri – >资源)之前调用过滤器.否则,RolesAllowedDynamicFeature注册的过滤器(在此阶段调用)将不会看到自定义的SecurityContext.

编辑2

Jersey用户指南 – Authorization – securing resources

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...