今天在用Postman測試接口,沒上Spring Security之前,GET類和POST類的接口都測試的好好!
接着在pom.xml添加的Security依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
並在application.yml中添加的Security配置:
security: user: name: user password: pwd123
通過以上配置使用上Spring Security后,GET類和POST類的接口都報未授權:
這個好理解:因為Security默認啟用了Basic Auth授權,接着我就在Postman的Authorization頁簽中設置Basic Auth授權基本信息:
填好授權信息后,清理Cookie再次請求,GET類請求一切正常:
然而,清理Cookie再次請求,POST類請求卻依舊不行:
首先,接口本身肯定是沒問題的,因為上Spring Security之前一切都挺好!其次,Spring Security本身肯定也是正常工作的,因為Postman中沒有進行授權前GET類的POST類的請求都不行!現在GET類的行了,POST類的卻不行~,那么這兩類請求肯定有不一樣的地方,讓Spring Security進行了攔截!
搗鼓了大半天,最后發現是Spring Security會對POST、PUT、PATCH等數據提交類的請求進行CSRF驗證(防止跨站請求偽造攻擊),Spring Security要求這些請求必須攜帶CSRFToken,但是目前Postman並不會利用Authorization頁簽中填上的Basic Auth相關信息生成CSRFToken。你得用自己的登錄接口來生成,並將生成的CSRFToken添加到Postman后續的各個測試請求的Headers中(X-CSRFToken)。
既然知道了原因,我們為了測試方便,我就不使用登錄接口拿CSRFToken,而是暫時將Spring Security的CSRF驗證關掉即可(交付測試和上生產時記得重新打開),添加Web安裝配置類繼承WebSecurityConfigurerAdapter適配器類,並重寫configure(HttpSecurity http)方法即可:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().csrf().disable(); } }
重新運行應用,清理Cookie再次請求,POST類請求也可以了: