在UserDetailsService的loadUserByUsername方法裏去構建當前登錄的用戶時,你能夠選擇兩種受權方法,即角色受權和權限受權,對應使用的代碼是hasRole和hasAuthority,而這兩種方式在設置時也有不一樣,下面介紹一下:spring
@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; } }
上面使用了兩種受權方法,你們能夠參考。app
@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設計者的考慮,兩種性質完成獨立的東西,不存在任何關係,一個是用作角色控制,一個是操做權限的控制,兩者也並不矛盾。ide