要使用Spring Security,首先固然是得要加上依賴spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
這個時候咱們不在配置文件中作任何配置,隨便寫一個Controller安全
@RestController public class TestController { @GetMapping("/hello") public String request() { return "hello"; } }
啓動項目,咱們會發現有這麼一段日誌app
2020-01-05 01:57:16.482 INFO 3932 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :ide
Using generated security password: 1f0b4e14-1d4c-4dc8-ac32-6d84524a57dcspring-boot
此時表示Security生效,默認對項目進行了保護,咱們訪問該Controller中的接口,會見到以下登陸界面spa
這裏面的用戶名和密碼是什麼呢?此時咱們須要輸入用戶名:user,密碼則爲以前日誌中的"1f0b4e14-1d4c-4dc8-ac32-6d84524a57dc",輸入以後,咱們能夠看到此時能夠正常訪問該接口.net
在老版本的Springboot中(好比說Springboot 1.x版本中),能夠經過以下方式來關閉Spring Security的生效,可是如今Springboot 2中已經再也不支持日誌
security: basic: enabled: false
固然像這種什麼都不配置的狀況下,實際上是使用的表單認證,如今咱們能夠把認證方式改爲HttpBasic認證(關於HTTP的幾種認證方式能夠參考HTTP協議整理 中的HTTP的常見認證方式)。orm
此時咱們須要在項目中加入這樣一個配置類blog
/** * WebSecurityConfigurerAdapter是Spring提供的對安全配置的適配器 * 使用@EnableWebSecurity來開啓Web安全 */ @Configuration @EnableWebSecurity public class SecrityConfig extends WebSecurityConfigurerAdapter { /** * 重寫configure方法來知足咱們本身的需求 * 此處容許Basic登陸 * @param http * @throws Exception */ @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic() //容許Basic登陸 .and() .authorizeRequests() //對請求進行受權 .anyRequest() //任何請求 .authenticated(); //都須要身份認證 } }
此時重啓項目,在訪問/hello,界面以下
輸入用戶名,密碼(方法與以前相同),則能夠正常訪問該接口。固然在這裏,咱們也能夠改回容許表單登陸。
@Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() //容許表單登陸 .and() .authorizeRequests() //對請求進行受權 .anyRequest() //任何請求 .authenticated(); //都須要身份認證 }
這樣又變回跟以前默認不配置同樣了。
SpringSecutiry基本原理
由上圖咱們能夠看到,Spring Security其實就是一個過濾器鏈,它裏面有不少不少的過濾器,就圖上的第一個過濾器UsernamePasswordAuthenticationFilter是用來作表單認證過濾的;若是咱們沒有配置表單認證,而是Basic認證,則第二個過濾器BasicAuthenticationFilter會發揮做用。最後一個FilterSecurityInterceptor則是用來最後一個過濾器,它的做用是用來根據前面的過濾器是否生效以及生效的結果來判斷你的請求是否能夠訪問REST接口。若是沒法經過FilterSecurityInterceptor的判斷的狀況下,會拋出異常。而ExceptionTranslationFIlter會捕獲拋出的異常來進行相應的處理。