Spring安全性@PreAurhorize hasRole()属性注入

假设我的spring安全性和属性配置正确,我想使用属性中的角色名称

@PreAuthorize("hasRole('${role.rolename}')") public void method() {} 

我在上面的代码示例中尝试过,但它不起作用(需要’$ {role.rolename}’字符串作为比较的角色)

如果我切换到

 @PreAuthorize("hasRole('ROLE_ADMIN')") public void method() {} 

它工作得很好。 我对这种用法的动机是在各种环境下的应用程序测试中具有更好的灵

尝试删除''标志:

 @PreAuthorize("hasRole(${role.rolename})") public void method() {} 

编辑。 我确信有更好的方法,但作为一种解决方法,您可以在某个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() {} 

我发现你可以直接获取propertyResolver并从中获取值,而不是像@Maksym所建议的那样编写自己的类。

Exammple:

 @PreAuthorize("hasRole(@environment.getProperty('role.rolename')") public void method() {} 

基于其他答案,有一件事让我失望,那就是没有在OAuth2MethodSecurityExpressionHandler上设置上下文。

确保在MethodSecurityConfig加载上述答案的上下文才能工作。

 @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Autowired private ApplicationContext context; @Override protected MethodSecurityExpressionHandler createExpressionHandler() { OAuth2MethodSecurityExpressionHandler handler = new OAuth2MethodSecurityExpressionHandler(); handler.setApplicationContext(context); return handler; } } 

然后你就可以成功访问了

 @PreAuthorize("hasRole(@environment.getProperty('role.rolename')") public void method() {}