如何创建用于spring安全表达式语言注释的自定义方法 [英] How to create custom methods for use in spring security expression language annotations
问题描述
我想创建一个类,通过注释添加自定义方法,以便在spring安全表达式语言中使用基于方法的授权。
I would like to create a class that adds custom methods for use in spring security expression language for method-based authorization via annotations.
例如,我想要创建一个像'customMethodReturningBoolean'这样的自定义方法,可以这样使用:
For example, I would like to create a custom method like 'customMethodReturningBoolean' to be used somehow like this:
@PreAuthorize("customMethodReturningBoolean()")
public void myMethodToSecure() {
// whatever
}
我的问题是这个。
如果可能,我应该创建自定义方法的子类,我将如何在spring xml配置文件中配置它,并且有人给我一个这样使用的自定义方法的示例? / p>
My question is this. If it is possible, what class should I subclass to create my custom methods, how would I go about configuring it in the spring xml configuration files and come someone give me an example of a custom method used in this way?
推荐答案
你需要继承两个类。
首先,设置一个新的方法表达式处理程序
First, set a new method expression handler
<global-method-security>
<expression-handler ref="myMethodSecurityExpressionHandler"/>
</global-method-security>
myMethodSecurityExpressionHandler
将是<$的子类c $ c> DefaultMethodSecurityExpressionHandler 覆盖 createEvaluationContext()
,设置 MethodSecurityExpressionRoot
的子类 MethodSecurityEvaluationContext
。
myMethodSecurityExpressionHandler
will be a subclass of DefaultMethodSecurityExpressionHandler
which overrides createEvaluationContext()
, setting a subclass of MethodSecurityExpressionRoot
on the MethodSecurityEvaluationContext
.
例如:
@Override
public EvaluationContext createEvaluationContext(Authentication auth, MethodInvocation mi) {
MethodSecurityEvaluationContext ctx = new MethodSecurityEvaluationContext(auth, mi, parameterNameDiscoverer);
MethodSecurityExpressionRoot root = new MyMethodSecurityExpressionRoot(auth);
root.setTrustResolver(trustResolver);
root.setPermissionEvaluator(permissionEvaluator);
root.setRoleHierarchy(roleHierarchy);
ctx.setRootObject(root);
return ctx;
}
这篇关于如何创建用于spring安全表达式语言注释的自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!