Spring security @PreAuthorize hasRole() properties injection

后端 未结 3 1729
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 15:49

Assuming that my Spring Security and properties are configured properly, I would like to use role name from property like

@PreAuthorize(\"hasRole(\'${role.ro         


        
3条回答
  •  青春惊慌失措
    2020-12-03 16:19

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

提交回复
热议问题