我的 JEE6 web 应用程序(主要是 CDI、EJB 3.1 和 JSF 2)使用 Spring Security 3,但不使用 Spring 依赖注入(inject)或 MVC。我实现了一个 Spring AuthenticationProvider 来处理登录。在登录过程中,我根据一些自定义业务逻辑向用户添加角色。
现在,我想使用 JSR 250 注释来保护我的业务逻辑。我的业务逻辑是使用无状态 EJB(版本 3.1)实现的。
我将 Spring 的上下文 XML 文件包含在 web.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();
正如预期的那样,权限集合不包含 ROLE_GROUP 权限。
看来我的注释被完全忽略了,但为什么呢?我也尝试了Spring的pre-post注解,但似乎也没有效果。
最佳答案
默认情况下,Spring Security 使用 standard Spring AOP ,仅限于由 Spring 应用程序上下文创建的 bean。生命周期不受 Spring 控制的对象(例如 EJB)不会受到影响。同样,如果您使用 new
创建对象实例,或其他一些框架会按需创建对象。
将方法安全拦截器应用于所有对象实例的唯一选择是使用 Aspectj。 this question的答案可能是一个很好的起点。
关于java - Spring Security + JSR 250 + EJB 3.1 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12680608/