Spring security @PreAuthorize hasRole() properties injection

此生再无相见时 提交于 2019-12-28 04:20:12

问题


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() {}

I have tried like in above code sample but it does not work (it takes '${role.rolename}' String as role to compare)

If I switch to

@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.


回答1:


Try to remove '' signs:

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

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() {}



回答2:


I've found that you can just grab the propertyResolver and pull values directly from that, instead of writing your own class as was suggested by @Maksym.

Exammple:

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



回答3:


Building on other answers here, one thing that tripped me up was not setting the context on the OAuth2MethodSecurityExpressionHandler.

Make sure that in your MethodSecurityConfig you're loading the context for the answers above to work.

@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;
    }
}

Then you can successfully access

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


来源:https://stackoverflow.com/questions/18207248/spring-security-preauthorize-hasrole-properties-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!