SpringSecurity设置角色和权限

在UserDetailsService使用loadUserByUsername构建当前登录用户时,可以选择两种授权方法,即角色授权和权限授权,对应使用的代码是hasRole和hasAuthority,而这两种方式在设置时也有不同,下面介绍一下:

  1. 角色授权:授权代码需要加ROLE_前缀,controller上使用时不要加前缀
  2. 权限授权:设置和使用时,名称保持一至即可
在UserDetailsService中设置权限:
@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"));//设置权限和角色
    // 1. commaSeparatedStringToAuthorityList放入角色时需要加前缀ROLE_,而在controller使用时不需要加ROLE_前缀
    // 2. 放入的是权限时,不能加ROLE_前缀,hasAuthority与放入的权限名称对应即可
    return user;
  }
}
在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";
}

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

//user角色
@GetMapping("/user-role")
@PreAuthorize("hasRole('USER')")
public String readUser() {
    return "have a user role";
}
原文地址:https://www.cnblogs.com/xlizi/p/13601320.html