2 回答

TA貢獻1871條經驗 獲得超8個贊
anyRequest()始終應用第一個匹配器,因為匹配器的順序很重要,請參見HttpSecurity#authorizeRequests:
注意匹配器是按順序考慮的。因此,以下內容無效,因為第一個匹配器匹配每個請求,并且永遠不會到達第二個映射:
http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**")
.hasRole("ADMIN")
您修改和簡化的配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/users/all").hasRole("admin")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.exceptionHandling().accessDeniedPage("/403");
}

TA貢獻2037條經驗 獲得超6個贊
問題在于配置時的規則順序HttpSecurity。發生的情況是當請求傳入并到達
authorizeRequests().anyRequest().authenticated()
由于用戶已通過身份驗證,因此永遠不會進入
.antMatchers("/users/all").hasRole("admin")
這是如何配置它的示例:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/public").permitAll()
.antMatchers("/user").hasRole("USER")
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.exceptionHandling().accessDeniedPage("/403");
}
它使用責任鏈模式。它將遍歷規則鏈,直到找到匹配的規則。永遠不會達到匹配規則之后的任何規則。通常,在編寫用于經過身份驗證的請求的規則時,將優先考慮更具體的規則。
添加回答
舉報