概念
在UserDetailsService的loadUserByUsername方法里去構建當前登陸的用戶時,你可以選擇兩種授權方法,即角色授權和權限授權,對應使用的代碼是hasRole和hasAuthority,而這兩種方式在設置時也有不同,下面介紹一下:
- 角色授權:授權代碼需要加ROLE_前綴,controller上使用時不要加前綴
- 權限授權:設置和使用時,名稱保持一至即可
使用,mock代碼
@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";
}
@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";
}
網上很多關於hasRole和hasAuthority的文章,很多都說二者沒有區別,但大叔認識,這是spring設計者的考慮,兩種性質完成獨立的東西,不存在任何關系,一個是用做角色控制,一個是操作權限的控制,二者也並不矛盾。