SpringSecurity設置角色和權(quan)限(xian)的注意點
概念
在UserDetailsService的loadUserByUsername方(fang)法里(li)去(qu)構建當(dang)前登(deng)陸(lu)的用(yong)戶(hu)時(shi)(shi),你可以選擇兩(liang)種(zhong)授(shou)(shou)權方(fang)法,即角色授(shou)(shou)權和(he)權限授(shou)(shou)權,對應使用(yong)的代碼是hasRole和(he)hasAuthority,而這兩(liang)種(zhong)方(fang)式在設(she)置時(shi)(shi)也有不同,下面介(jie)紹一下:
- 角色授權:授權代碼需要加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;
}
}
上面使用了兩種授權方法(fa),大家可(ke)以(yi)參考。
在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";
}
網(wang)上(shang)很(hen)(hen)多關于hasRole和hasAuthority的文章,很(hen)(hen)多都說(shuo)二者沒有區(qu)別,但大叔認識(shi),這是spring設計者的考慮,兩種(zhong)性(xing)質(zhi)完成獨立的東西(xi),不存在(zai)任何關系,一(yi)個(ge)是用(yong)做角色(se)控(kong)制,一(yi)個(ge)是操作權限的控(kong)制,二者也并不矛盾。