你如何解析 spring (web) 安全表达式,例如hasRole('admin')
以编程方式(不使用标签、注释或...
)? (参考文档 http://docs.spring.io/autorepo/docs/spring-security/3.2.0.RELEASE/reference/htmlsingle/#el-access)
我发现了Spring:使用什么解析器来解析安全表达式 https://stackoverflow.com/questions/3048623/spring-what-parser-to-use-to-parse-security-expressions- 但我不知道如何找到或构建EvaluationContext
例如在弹簧控制器内。
无需提供EvaluationContext
gives
org.springframework.expression.spel.SpelEvaluationException: EL1011E:(pos 0): Method call: Attempted to call method hasRole(java.lang.String) on null context object
您需要添加一些东西才能使其正常工作。您必须插入 Spring 的安全 API。这是我的做法,它在 Spring 3.2 中运行良好。
首先,正如之前所述,您必须在 spring-context.xml 中具有类似的配置:
<security:http access-decision-manager-ref="customAccessDecisionManagerBean">
<security:http/>
<bean id="customWebSecurityExpressionHandler"
class="com.boyan.security.CustomWebSecurityExpressionHandler"/>
<bean id="customAccessDecisionManagerBean"
class="org.springframework.security.access.vote.AffirmativeBased">
<property name="decisionVoters">
<list>
<bean class="org.springframework.security.web.access.expression.WebExpressionVoter">
<property name="expressionHandler" ref="customWebSecurityExpressionHandler" />
</bean>
</list>
</property>
</bean>
这定义了一个新的 expressionHandler 来覆盖 WebExpressionVoter 的默认表达式处理程序。然后我们将这个新的决策投票者添加到决策管理器中。 CustomWebSecurityExpressionHandler 的目的是控制SecurityExpressionRoot 的创建。到目前为止,一切都很好。问题是为什么您需要 CustomWebSecurityExpressionRoot ,答案很简单 - 您在那里定义自定义安全方法。考虑到这一点,我们可以编写以下类:
public class CustomWebSecurityExpressionHandler extends DefaultWebSecurityExpressionHandler {
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(
Authentication authentication, FilterInvocation fi) {
CustomWebSecurityExpressionRoot expressionRoot =
new CustomWebSecurityExpressionRoot(authentication, delegationEvaluator);
return expressionRoot;
}
}
}
public class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {
public CustomWebSecurityExpressionRoot(Authentication auth, FilterInvocation fi) {
super(auth, fi);
}
// in here you must define all of the methods you are going to invoke in @PreAuthorize
// for example if you have an expression with @PreAuthorize('isBoyan(John)')
// then you must have the following method defined here:
public boolean isBoyan(String value) {
//your logic goes in here
return "Boyan".equalsIgnoreCase(value);
}
}
如果您想获取对 ExpressionParser 的引用,可以使用以下方法 AbstractSecurityExpressionHandler.getExpressionParser()。可通过 CustomWebSecurityExpressionHandler 访问它。如果你想做一些更具体的事情,你也可以看看它的 API。
我希望这能回答你的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)