与安全相关的表达式在 Spring 中的操作集非常有限。您可以通过提供org.springframework.security.access.expression.SecurityExpressionOperations
接口的自定义实现来扩展此集合。以下是如何执行此操作的简要指南:
- 创建包装器
SecurityExpressionOperations
并实现所需的操作:
class MySecurityExpressionOperations implements SecurityExpressionOperations {
private SecurityExpressionOperations delegate;
public MySecurityExpressionOperations(SecurityExpressionOperations delegate) {
this.delegate = delegate;
}
public boolean hasProducts() {
MyUser user = (MyUser) delegate.getAuthentication().getPrincipal();
return !user.getProductList().isEmpty();
}
// Other methods
}
- 扩展
org.springframework.security.web.access.expression.WebExpressionVoter
和替换标准表达式处理程序:
class MyWebExpressionVoter extends WebExpressionVoter {
public MyWebExpressionVoter() {
setExpressionHandler(new DefaultWebSecurityExpressionHandler() {
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) {
SecurityExpressionOperations delegate = super.createSecurityExpressionRoot(authentication, fi);
return new MySecurityExpressionOperations(delegate);
}
});
}
}
- 提供自定义访问决策管理器:
<bean id="affirmativeBased" class="org.springframework.security.access.vote.AffirmativeBased">
<constructor-arg>
<list>
<bean class="my.company.MyWebExpressionVoter"/>
</list>
</constructor-arg>
</bean>
- 应用自定义访问决策管理器:
<http pattern="/**" use-expressions="true" access-decision-manager-ref="affirmativeBased">
<!-- ... -->
</http>
- 使用额外的安全操作保护 URL 之一:
<intercept-url pattern="/products" access="hasProducts()"/>