谢谢ericacm,但是由于以下几个原因它不起作用:
- DefaultMethodSecurityExpressionHandler的属性是私有的(反射可见性不理想)
- 至少在我的Eclipse中,我无法解析MethodSecurityEvaluationContext对象
区别在于,我们调用现有的createEvaluationContext方法,然后添加我们的自定义根对象。最后,我刚刚返回了StandardEvaluationContext对象类型,因为MethodSecurityEvaluationContext无法在编译器中解析(它们都来自同一接口)。这是我现在在生产中使用的代码。
使MethodSecurityExpressionHandler使用我们的自定义根目录:
public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler {
// parent constructor
public CustomMethodSecurityExpressionHandler() {
super();
}
/**
* Custom override to use {@link CustomSecurityExpressionRoot}
*
* Uses a {@link MethodSecurityEvaluationContext} as the <tt>EvaluationContext</tt> implementation and
* configures it with a {@link MethodSecurityExpressionRoot} instance as the expression root object.
*/
@Override
public EvaluationContext createEvaluationContext(Authentication auth, MethodInvocation mi) {
// due to private methods, call original method, then override it's root with ours
StandardEvaluationContext ctx = (StandardEvaluationContext) super.createEvaluationContext(auth, mi);
ctx.setRootObject( new CustomSecurityExpressionRoot(auth) );
return ctx;
}
}
这通过扩展SecurityExpressionRoot替换了默认根。在这里,我将hasRole重命名为hasEntitlement:
public class CustomSecurityExpressionRoot extends SecurityExpressionRoot {
// parent constructor
public CustomSecurityExpressionRoot(Authentication a) {
super(a);
}
/**
* Pass through to hasRole preserving Entitlement method naming convention
* @param expression
* @return boolean
*/
public boolean hasEntitlement(String expression) {
return hasRole(expression);
}
}
最后,更新securityContext.xml(并确保已从您的applcationContext.xml中引用了它):
<!-- setup method level security using annotations -->
<security:global-method-security
jsr250-annotations="disabled"
secured-annotations="disabled"
pre-post-annotations="enabled">
<security:expression-handler ref="expressionHandler"/>
</security:global-method-security>
<!--<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">-->
<bean id="expressionHandler" class="com.yourSite.security.CustomMethodSecurityExpressionHandler" />
注意: @Secured批注将通过其他验证处理程序运行,因此不会接受此替代。因此,在上面的xml中,我禁用了它们以防止以后出现混乱。