Spring Security + JSR 250 + EJB 3.1无法正常工作

时间:2012-10-01 20:31:27

标签: java spring-security ejb-3.1 jsr250

我的JEE6 webapp(主要是CDI,EJB 3.1和JSF 2)使用Spring Security 3,但不使用Spring依赖注入或MVC。我实现了一个Spring AuthenticationProvider来处理登录。在登录期间,我根据一些自定义业务逻辑向我的用户添加角色。

现在,我想使用JSR 250注释来保护我的业务逻辑。我的业务逻辑是使用无状态EJB(版本3.1)实现的。

我在web.xml中包含Spring的上下文XML文件,如下所示:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/applicationContext-security.xml
    </param-value>
</context-param>

以下是XML文件的内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:security="http://www.springframework.org/schema/security"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-3.1.xsd">


<security:global-method-security jsr250-annotations="enabled"/>

<security:http auto-config="false">
    <security:intercept-url pattern="/pages/**" access="ROLE_USER"/>
    <security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <security:form-login login-page="/login.jsf"/>
    <security:anonymous/>
    <security:custom-filter ref="logoutFilter" position="LOGOUT_FILTER"/>
</security:http>

<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
    <constructor-arg index="0" value="/login.jsf"/>
    <constructor-arg index="1">
        <list>
            <bean id="customLogoutHandler" class="com.example.client.security.CustomLogoutHandler"/>
            <bean id="securityContextLogoutHandler" class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
        </list>
    </constructor-arg>
    <property name="filterProcessesUrl" value="/logout.jsf"/>
</bean>

<security:authentication-manager>
    <security:authentication-provider ref="customAuthenticationProvider"/>
</security:authentication-manager>

<bean id="customAuthenticationProvider"
      class="com.example.client.security.CustomAuthenticationProvider"/>
</beans>

在我的课程中,我使用类注释(类型级别)来说明只有具有特定角色的用户才能访问所有方法:

@Model
@RolesAllowed("ROLE_GROUP")
public class UserListAction {

但是,只有角色ROLE_USER的用户也可以访问此类的任何功能。我在使用以下代码进行调试时验证了用户没有错误的角色:

    Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();

正如所料,authority集合不包含ROLE_GROUP权限。

看来我的注释完全被忽略了,但为什么呢?我也尝试过Spring的帖子后注释,但它们似乎也没有效果。

1 个答案:

答案 0 :(得分:1)

默认情况下,Spring Security使用standard Spring AOP,它仅限于由Spring应用程序上下文创建的bean。生命周期不受Spring控制的对象(如EJB)不会受到影响。同样,如果使用new创建对象实例,或者某个其他框架根据需要创建对象。

将方法安全拦截器应用于所有对象实例的唯一选择是使用Aspectj。 this question的答案可能是一个很好的起点。