原文:https://blog.csdn.net/tianlong1569/article/details/108398149
HttpSecurity全名為org.springframework.security.config.annotation.web.builders.HttpSecurity
這個類是Spring Security中繼承WebSecurityConfigurerAdapter時需要復寫的接口中的一個重要參數,用於配置Security重要的攔截及權限控制。這方法在父類中保護方法。
同時這個類也是OAuth2.0中資源服務繼承ResourceServerConfigurerAdapter時,需要復寫的接口中的一個重要參數。也是用於配置Security的重要攔截及權限。因此當我們使用Security及OAuth2.0時會有配置重復的問題。這點需要注意。這個方法在父類中屬於公開方法。
HttpSecurity 重要方法:
requestMatchers()
取得RequestMatcherConfigurer對象並配置允許過濾的路由;如requestMatchers().anyRequest()等同於http.authorizeRequests().anyRequest().access("permitAll");如下面兩個例子:
@Override
public void configure(HttpSecurity http) throws Exception {
//只允許路由由test開頭的需要進行權限認證,其他的接口不需要權限認證;requestMatchers().anyRequest()即所有接口可以不進行認證;
http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/test/*").authenticated();
}
@Override
public void configure(HttpSecurity http) throws Exception {
//只有以/test 開頭的路由需要進行權限認證;其他路由不需要權限認證
http.requestMatchers().antMatchers("/test/**").and().authorizeRequests().antMatchers("/**").authenticated();
}
上面兩個例子中可以看出:http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/test/").authenticated();配置和http.requestMatchers().antMatchers("/test/").and().authorizeRequests().antMatchers("/**").authenticated();配置后的效果是完全一樣的。
authorizeRequests()
授權管理控制的方法,這個方法返回一個ExpressionUrlAuthorizationConfigurer
//所有接口都不需要權限認證
http.authorizeRequests().antMatchers("/**").permitAll();
//所有接口都要進行權限認證
http.authorizeRequests().antMatchers("/**").authenticated();
//只有以test開頭的接口需要進行權限認證
http.authorizeRequests().antMatchers("/test/**").authenticated();
http.authorizeRequests().antMatchers("/test/").hasRole("user").antMatchers("/").authenticated();在這個代碼中要求以/test開頭的路由需要進行角色認證(這里要求user角色),而其他接口只要登錄即可訪問。當我們需要配置多個角色時可以通過hasAnyRole方法配置多個角色的訪問權限,如
http.authorizeRequests().antMatchers("/test/**").hasAnyRole("user","admin").antMatchers("/**").authenticated();