Notes on setting roles and permissions in spring security

concept

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

@Component
public class MyUserDetailService implements UserDetailsService {
  @Autowired
  private PasswordEncoder passwordEncoder;

  @Override
  public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
    User user = new User(name,
        passwordEncoder.encode("123456"),
        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

 @GetMapping("/write")
  @PreAuthorize("hasAuthority('write')")
  public String getWrite() {
    return "have a write authority";
  }

  @GetMapping("/read")
  @PreAuthorize("hasAuthority('read')")
  public String readDate() {
    return "have a read authority";
  }

  @GetMapping("/read-or-write")
  @PreAuthorize("hasAnyAuthority('read','write')")
  public String readWriteDate() {
    return "have a read or write authority";
  }

  @GetMapping("/admin-role")
  @PreAuthorize("hasRole('admin')")
  public String readAdmin() {
    return "have a admin role";
  }

  @GetMapping("/user-role")
  @PreAuthorize("hasRole('USER')")
  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