spring security 配置了訪問權限管控
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
// 定制請求的授權規(guī)則
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
然后前端登陸,訪問需要權限的地址時出現(xiàn)
403 Forbidden
后臺代碼調(diào)試發(fā)現(xiàn),報錯信息如下:(拒絕訪問(用戶不是匿名的);委托給Access Dead處理程序)
2018-10-12 16:22:30.101 DEBUG 2200 --- [http-nio-8080-exec-7] o.s.s.w.a.ExceptionTranslationFilter :
Access is denied (user is not anonymous); delegating to AccessDeniedHandler
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
即用戶沒有訪問的權限。
然后將調(diào)試信息往上翻了一下發(fā)現(xiàn)了如下內(nèi)容:
2018-10-12 16:31:56.335 DEBUG 2200 --- [http-nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /user; Attributes: [hasRole('ROLE_USER')]
2018-10-12 16:22:30.099 DEBUG 2200 --- [http-nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /admin/; Attributes: [hasRole('ROLE_ADMIN')]
原來他會把設置的角色名自動加上 ‘ ROLE_ ’ 前綴。
所以在數(shù)據(jù)庫中將角色名設置為帶 ‘ ROLE_ ’ 前綴的值便能成功訪問限制的地址
| id | role_name |
|---|---|
| 1 | ROLE_ADMIN |
| 2 | ROLE_USER |
也可以在取值后添加 ‘ ROLE_ ’ 通過驗證