在UserDetailsService使用loadUserByUsername構建當前登錄用戶時,可以選擇兩種授權方法,即角色授權和權限授權,對應使用的代碼是hasRole和hasAuthority,而這兩種方式在設置時也有不同,下面介紹一下:
- 角色授權:授權代碼需要加ROLE_前綴,controller上使用時不要加前綴
- 權限授權:設置和使用時,名稱保持一至即可
在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";
}