Spring security added prefix “ROLE_” to all roles name?

前端 未结 5 1537
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 12:00

I have this code in my Web Security Config:

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 12:46

    You can create a mapper to add _ROLE at the beginning of all of your roles:

    @Bean
    public GrantedAuthoritiesMapper authoritiesMapper() {
        SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
        mapper.setPrefix("ROLE_"); // this line is not required 
        mapper.setConvertToUpperCase(true); // convert your roles to uppercase
        mapper.setDefaultAuthority("USER"); // set a default role
    
        return mapper;
    }
    

    The you should add the mapper to your provider:

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        // your config ...
        provider.setAuthoritiesMapper(authoritiesMapper());
    
        return provider;
    }
    

提交回复
热议问题