Notes on setting roles and permissions in spring security


In the loadUserByUsername method of UserDetailsService to build the current login user, you can choose two authorization methods, role authorization and permission authorization. The corresponding codes are hasRole and hasAuthority, and the two methods are different when setting. Next, I will introduce:

  1. ROLE authorization: the authorization code needs to be prefixed with "ROLE" and not with "ROLE" when used on the controller
  2. Authority authorization: when setting and using, the name can be kept one to

Use, mock code

public class MyUserDetailService implements UserDetailsService {
  private PasswordEncoder passwordEncoder;

  public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
    User user = new User(name,
        AuthorityUtils.commaSeparatedStringToAuthorityList("read,ROLE_USER"));//Set permissions and roles
    // 1. commaSeparatedStringToAuthorityList needs to be prefixed with ROLE, while controller does not need to be prefixed with ROLE
    // 2. When the permission is put in, the prefix ROLE "cannot be added. The hasAuthority corresponds to the permission name put in
    return user;

Two authorization methods are used above. You can refer to them.

Add permission control to method in controller

  public String getWrite() {
    return "have a write authority";

  public String readDate() {
    return "have a read authority";

  public String readWriteDate() {
    return "have a read or write authority";

  public String readAdmin() {
    return "have a admin role";

  public String readUser() {
    return "have a user role";

There are many articles about hasRole and hasAuthority on the Internet, many of which say that there is no difference between them, but Uncle knows that this is the consideration of spring designers. There is no relationship between the two natures to complete independent things. One is to use for role control, the other is to control the operation authority, and the two are not contradictory.

Tags: Java Spring

Posted on Wed, 04 Dec 2019 04:27:51 -0500 by rajb