How do I remove the ROLE_ prefix from Spring Security with JavaConfig?

后端 未结 7 1176
灰色年华
灰色年华 2020-12-01 16:22

I\'m trying to remove the \"ROLE_\" prefix in Spring Security. The first thing I tried was:

http.servletApi().rolePrefix(\"\");

That didn\'

7条回答
  •  日久生厌
    2020-12-01 16:51

    With Spring Boot 2.3 I got this exception at boot time:

    Error creating bean with name 'resourceHandlerMapping' defined in class path resource 
    [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]:
    Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
    Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: 
    Factory method 'resourceHandlerMapping' threw exception;
    nested exception is java.lang.IllegalStateException: No ServletContext set
    

    Here is my solution:

    @Configuration
    @Import(RolePrefixConfiguration.class)
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
    public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
      public static class RolePrefixConfiguration {
    
        @Bean
        public GrantedAuthorityDefaults grantedAuthorityDefaults() {
          log.debug("remove prefix 'ROLE_' from grantedAuthorityDefaults");
          return new GrantedAuthorityDefaults("");
        }
    
      }
       
       // ... your usual config 
    }
    

提交回复
热议问题