【发布时间】:2020-02-09 22:03:52
【问题描述】:
我有一个像下面这样的自定义权限类,我将其用于@PreAuthorize 的方法安全性,它工作正常,但我需要根据此类中的一些业务逻辑添加自定义响应标头,如果有人可以提出一些建议在这方面,它将有很大帮助。
在控制器上
@PreAuthorize("hasPermission('APP', 'GENERIC', 'VIEW')")
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler =
new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator());
return expressionHandler;
}
}
public class CustomPermissionEvaluator implements PermissionEvaluator {
boolean dev = true;
public CustomPermissionEvaluator() {
}
public void init() {
}
@Override
public boolean hasPermission(
Authentication auth, Object targetDomainObject, Object permission) {
System.out.println("CustomPermissionEvaluator.hasPermission()-X");
if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)){
return false;
}
String targetType = targetDomainObject.getClass().getSimpleName().toUpperCase();
return hasPrivilege(auth, "X",targetType, permission.toString().toUpperCase());
}
@Override
public boolean hasPermission(
Authentication auth, Serializable category, String module, Object permission) {
String cat = (String) category;
System.out.println("CustomPermissionEvaluator.hasPermission()-Y "+module);
if ((auth == null) || StringUtils.isEmpty(module) || !(permission instanceof String)) {
return false;
}
return hasPrivilege(auth, cat,module.toUpperCase(), permission.toString().toUpperCase());
}
}
【问题讨论】:
-
嗯,很简单,除了“hasPermission(...)”之外,你不能调用其他方法,在“PermissionEvaluator”上返回一个布尔值,生成响应头是控制器类的职责。因此,如果您的 PermissionEvaluator 和控制器之间有共同的逻辑,只需将逻辑放在共同的依赖项中。
-
或者,如果我能够在某些过滤器中提取这些 haspermission 方法参数值也足够了。是否可以在过滤器中检索该值?
-
我认为您应该向我们展示您如何调用这些“hasPermission(...)”方法。
-
好的,修改了我的问题,添加了另一个调用评估器的类以及控制器中使用的注释
标签: spring spring-boot spring-mvc spring-security spring-annotations