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

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

    What Divelnto, zapl and thorinkor said is right. But the question should be about "Role" and NOT "Roles". OR, if you are having users and roles into one table, its a bad design. You might want to take a relook at your design approach. You should have a separate role entity. And in your UserService you can do something like:

    AppUser user = userRepository.findByUsername(username);
    
    Set grantedAuthorities = new HashSet<>(); // use list if you wish
    for (AppRole role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    }
    return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            grantedAuthorities
    );
    

    Samples: sample1 sample2 sample3

    In DB, you can store role name as - (e.g.) ADMIN/EDITOR/VIEWER in the database or store roles as ROLE_ADMIN/ROLE_... then you might wanna use hasRole/hasAuthoriy. Hope it helps.

    For reference, take a look at here:

    Spring Security Related 1

    Spring Security Related 2

提交回复
热议问题