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

后端 未结 3 658
小蘑菇
小蘑菇 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:09

    For adding Roles you need to have a table containing username and its corresponding role.
    Suppose a user has two roles namely, ADMIN and USER

    One User can have multiple roles.

    @Override
    public Collection getAuthorities() {
        final List authorities = new LinkedList<>();
        if (enabled) {
            if (this.getUser().isAdmin()) {
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
            return authorities;
    }
    

    This can be called as,

    private UsernamePasswordAuthenticationToken getAuthentication(
    final String token, final HttpServletRequest req,
    final HttpServletResponse res){
        return new UsernamePasswordAuthenticationToken(userAccount, null,
        userAccount.getAuthorities());
    }
    

提交回复
热议问题