[英]Spring Boot -- Post request with CSRF token produce 403 error
我正在嘗試在我的 Spring 引導 API 中實現 CSRF 令牌安全性以了解如何處理它。
我遵循了本教程(服務器端部分) ,這是我的安全配置:
private static final String[] CSRF_IGNORE = {"/api/login"};
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.ignoringAntMatchers(CSRF_IGNORE)
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(new CustomCsrfFilter(), CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint() {
})
.and()
.authenticationProvider(getProvider())
.formLogin()
.loginProcessingUrl("/api/login")
.successHandler(new AuthentificationLoginSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
.invalidateHttpSession(true)
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
其他內容與教程中的相同。
我正在使用 Postman 進行測試。
當我在CSRF_IGNORE添加我想要的端點時,我可以通過 logger/debug 看到存儲的令牌,並且來自 cookie 的令牌是相同的,因為使用了.addFilterAfter()中的安全配置部分CustomCsrfFilter.java ,但是當我刪除來自這個 CSRF_IGNORE 的端點,我得到的是 403,並且沒有使用CustomCsrfFilter.java中的記錄器/調試,所以我認為沒有比較令牌。
我想我錯過了一些東西,我想理解。
如果您想將 CSRF 與 http 僅使用錯誤 cookie 一起使用,為什么不使用 Spring Security 內置的CookieCsrfTokenRepository
呢? 應該以這種方式簡化您的配置。 CustomCsrfFilter
似乎正在將XSRF-TOKEN
cookie 添加到HttpServletResponse
, CookieCsrfTokenRepository
會為您執行此操作。
使用CookieCsrfTokenRepository
時的默認 CSRF cookie 名稱是X-CSRF-TOKEN
,這是 Angular 的HttpClientXsrfModule
使用的默認名稱。 當然,如果您需要,您可以自定義它。
所以你的安全配置變成:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint())
.and()
.authenticationProvider(getProvider())
.formLogin()
.loginProcessingUrl("/api/login")
.successHandler(new AuthentificationLoginSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
.invalidateHttpSession(true)
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
並且使用 Angular,您的應用程序模塊具有HttpClientXsrfModule
作為
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
HttpClientXsrfModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.