2 回答

TA貢獻(xiàn)1871條經(jīng)驗 獲得超8個贊
anyRequest()始終應(yīng)用第一個匹配器,因為匹配器的順序很重要,請參見HttpSecurity#authorizeRequests:
注意匹配器是按順序考慮的。因此,以下內(nèi)容無效,因為第一個匹配器匹配每個請求,并且永遠(yuǎn)不會到達(dá)第二個映射:
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貢獻(xiàn)2037條經(jīng)驗 獲得超6個贊
問題在于配置時的規(guī)則順序HttpSecurity。發(fā)生的情況是當(dāng)請求傳入并到達(dá)
authorizeRequests().anyRequest().authenticated()
由于用戶已通過身份驗證,因此永遠(yuǎn)不會進(jìn)入
.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");
}
它使用責(zé)任鏈模式。它將遍歷規(guī)則鏈,直到找到匹配的規(guī)則。永遠(yuǎn)不會達(dá)到匹配規(guī)則之后的任何規(guī)則。通常,在編寫用于經(jīng)過身份驗證的請求的規(guī)則時,將優(yōu)先考慮更具體的規(guī)則。
添加回答
舉報