如何使用/配置JAX-RS 2.0,SpringSecurity 3.1。+,EJB 3.2

时间:2013-11-12 15:36:33

标签: spring-security jax-rs glassfish-4 java-ee-7 ejb-3.2

我目前正在尝试使用这些主要技术设置项目:

  • Java EE 7
  • EJB 3.2
  • JAX-RS(Jersey)2.0
  • Glassfish 4
  • Spring Security 3.1.5

我看到有可能写出那样的东西

@Stateless
@Path("apath")
public class WebResource {
    @EJB
    private SomeService serviceInjected;

    @GET
    public Response doSomething() {
        return Response.ok(injectedService.doSomethingElse()).build();
    }
}

然后,这意味着SomeService会话Bean由容器注入,一旦我们调用路径:: /// apath,一切正常。

现在,我尝试实现的是将SpringSecurity框架集成到该代码中。所以我的代码变成了这个:

@Component
@Stateless
@Path("apath")
public class WebResource {
    @EJB
    private SomeService serviceInjected;

    @GET
    @PreAuthorized("hasPermission('ROLE_SOMETHING')")
    public Response doSomething() {
        return Response.ok(injectedService.doSomethingElse()).build();
    }
}

但是,这不起作用。除了SpringSecurity注释之外的所有内容都继续有效。授权注释不会被考虑在内。

在SpringSecurity配置文件中,我有类似的东西:

<security:global-method-security
    access-decision-manager-ref="preVoteAccessDecisionManager"
    pre-post-annotations="enabled" />

包含与过滤器链相关的所有内容,因此配置正确。例如,我有:

<beans:bean id="securityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
    <beans:property name="securityMetadataSource">
        <security:filter-security-metadata-source>
            <security:intercept-url pattern="/**" access="ROLE_TEST" />
        </security:filter-security-metadata-source>
    </beans:property>
    <beans:property name="authenticationManager" ref="authenticationManager" />
    <beans:property name="accessDecisionManager" ref="accessDecisionManager" />
</beans:bean>

我在Glassfish 4服务器日志中看到,SpringSecurity为我的身份验证用户管理了ROLE_TEST访问。我还看到我的用户通过身份验证了我期望的角色列表。

我也尝试使用此配置并依赖于javax.annotation.security注释,如下所示:

<security:global-method-security
    access-decision-manager-ref="preVoteAccessDecisionManager"
    jsr250-annotations="enabled" />

@Stateless
@Path("apath")
public class WebResource {
    @EJB
    private SomeService serviceInjected;

    @GET
    @RolesAllowed("ROLE_SOMETHING")
    public Response doSomething() {
        return Response.ok(injectedService.doSomethingElse()).build();
    }
}

这次,注释正在运行,并且在对用户进行身份验证时会引发异常。但在这种情况下,我的用户具有角色,但容器使用的SecurityContext没有填充与SpringSecurity认证的用户相关的Principal和角色信息。

最后,我的问题。有没有办法将JAX-RS / @Stateless / SpringSecurity授权集成在一起?如果没有,有没有办法从SrpingSecurity填充SecurityContext以允许javax.annotation.security像魅力一样工作?

提前感谢任何可以解决我问题的帮助,提示,技巧或其他任何事项:D

1 个答案:

答案 0 :(得分:1)

Spring Security的方法安全注释通常只适用于生命周期由Spring控制的Spring bean。这不包括EJB。但是,如果您希望可以使用AspectJ集成,它将适用于任何对象,包括EJB实例。 Spring Security代码库中有一个sample application,您可以将其用作参考。也许值得考虑是否需要使用EJB。