如何在Jersey Web服务中检查经过身份验证的用户的角色

时间:2013-05-06 09:40:31

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

环境:Jersey 1.17,GlassFish 3.1.2.2,JDK 6u31。

web.xml 安全段:

<security-constraint>
    <display-name>SSL transport</display-name>
    <web-resource-collection>
        <web-resource-name>Secure Area</web-resource-name>
        <description></description>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>USER</role-name>
        <role-name>ADMIN</role-name>
    </auth-constraint>
    <user-data-constraint>
        <description></description>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>myRealm</realm-name>
</login-config>

sun-web.xml中

<security-role-mapping>
    <role-name>USER</role-name>
    <group-name>USER</group-name>
</security-role-mapping>
<security-role-mapping>
    <role-name>ADMIN</role-name>
    <group-name>ADMIN</group-name>
</security-role-mapping>

我正在使用注入来获取SecurityContext实例:

@Context
private SecurityContext sec;

现在我应该能够使用SecurityContext#isUserInRole(String role)方法检查Web服务方法中的角色,但无论指定为什么参数,返回的值始终为false

我可以使用SecurityContext#getUserPrincipal()方法检索经过身份验证的用户名。

这可能是什么问题?还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

我还必须分别在web.xml中指定安全角色:

<!-- after <login-config /> -->
<security-role>
    <role-name>USER</role-name>
</security-role>
<security-role>
    <role-name>ADMIN</role-name>
</security-role>