我們在使用spring Security時,需要注意authorizeRequests的順序
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.antMatchers("/hello").permitAll();
}
由於是按照從上往下順序依次執行,如上所示,當我們訪問/hello時,會發現此時仍然需要登錄!
所以我們往往會把.anyRequest().authenticated()放在最后
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/hello").hasRole("USER")
.antMatchers("/hi").hasRole("ADMIN")
.anyRequest().authenticated();
}
如上就表示。訪問/hello接口需要USER角色,訪問/hi需要ADMIN角色,訪問其他接口需要認證。
那么訪問/hello和/hi不需要認證嗎?
也需要,畢竟只有認證了,我們才能從authentication中獲得角色信息!