本文介绍了Spring security @PreAuthorize hasRole() 属性注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的 Spring Security 和属性配置正确,我想使用来自属性的角色名称
Assuming that my Spring Security and properties are configured properly, I would like to use role name from property like
@PreAuthorize("hasRole('${role.rolename}')")
public void method() {}
我在上面的代码示例中尝试过,但它不起作用(它需要 '${role.rolename}' 字符串作为要比较的角色)
I have tried like in above code sample but it does not work (it takes '${role.rolename}' String as role to compare)
如果我切换到
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void method() {}
它工作得很好.我这样使用的动机是在各种环境下的应用程序测试中具有更好的灵活性.
it works just fine.My motivation to such usage is better flexibility in application tests on various environments.
推荐答案
尝试删除 ''
符号:
@PreAuthorize("hasRole(${role.rolename})")
public void method() {}
编辑.我确信有更好的方法,但作为一种解决方法,您可以在某个 bean 上调用一些方法:
EDIT. I am sure that there is a better way, but as a workaround you can call some method on some bean:
@Component("appVariablesHolder")
public class AppVariablesHolder {
@Value("${role.rolename}")
private String someRole;
public String getSomeRole() {
return this.someRole;
}
}
@PreAuthorize("hasRole(@appVariablesHolder.getSomeRole())")
public void method() {}
这篇关于Spring security @PreAuthorize hasRole() 属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!