如何创建用于 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 配置文件中配置它并且有人给我一个以这种方式使用的自定义方法的示例?
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?
推荐答案
您需要对两个类进行子类化.
You'll need to subclass two classes.
首先,设置一个新的方法表达式处理程序
First, set a new method expression handler
<global-method-security>
<expression-handler ref="myMethodSecurityExpressionHandler"/>
</global-method-security>
myMethodSecurityExpressionHandler
将是 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屋!