今日學習spring boot的安全框架spring security ,做了個demo ,實現登錄驗證和訪問授權功能,好記性不如爛博客,在此做個筆記!
先說遇到的坑吧:
1. PasswordEncoder 密碼加密方式問題:There is no PasswordEncoder mapped for the id "null"
2. auth.userDetailsService(customUserService()) 方式下的 new SimpleGrantedAuthority(roles.getRname()) roles前綴問題,roles的數據庫里必須存成像:ROLE_admin,ROLE_user
必須要 ROLE_ 前綴, 因為 hasRole("user")時會自動加上ROLE_前綴變成 ROLE_user ,如果不加前綴一般就會出現403錯誤。
3. SysUser 和 Roles 實體類中的屬性 name字段不能相同,一般可以是這樣 SysUser - >>> sname , Roles ->>> rname 這樣mybatis字段組裝對象時不會出莫名的錯誤。
4. 自定義 SecurityConfig 實現 WebSecurityConfigurerAdapter 時在類名前加注解,@EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true)
prePostEnabled = true 屬性設置后控制器層的方法前的@PreAuthorize("hasRole('admin')") 注解才能起效。
代碼:鏈接: https://pan.baidu.com/s/1mY1p50Fx7afDCTmEM9QOHA 密碼: xyk4