Spring Security/Spring Boot - How to set ROLES for users

后端 未结 3 632
小蘑菇
小蘑菇 2021-01-31 11:43

When I logged in using security, I cannot use the request.isUserInRole() method. I think the roles of the users was not set.

This is my Security Configurati

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 12:04

    You should fill in the content of role by yourself when creating your UserDetails:

    public class SecurityUser implements UserDetails{
        String ROLE_PREFIX = "ROLE_";
    
        String userName;
        String password;
        String role;
    
        public SecurityUser(String username, String password, String role){
            this.userName = username;
            this.password = password;
            this.role = role;
        }
    
        @Override
        public Collection getAuthorities() {
            List list = new ArrayList();
    
            list.add(new SimpleGrantedAuthority(ROLE_PREFIX + role));
    
            return list;
        }
    

    Basically, what you need to do is override method: getAuthorities, and fill in the content of your role field into the GrantedAuthority list.

提交回复
热议问题