首页 > 解决方案 > 如何增强对现有 spring boot 和 anjularjs 应用程序的 csrf 保护?

问题描述

我需要为我现有的 Spring Boot 应用程序添加 csrf 保护,其中 angularJS 是客户端框架。

标签: angularjsspring-bootcsrf

解决方案


spring-security 需要设置 cookie 'XSRF-TOKEN' 但不在 HttpOnly 中。然后 Angular 的 javascript 将读取 cookie 并将其添加到传出 http 请求的标头中。

在你的 spring-boot 代码库中应该有一个类似于:

@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // class content }

在这个类中应该有一个以“http”开头的链。

在这个链中添加 .csrf(csrf -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) )

来自文档:“默认情况下,CookieCsrfTokenRepository 将写入名为 XSRF-TOKEN 的 cookie,并从名为 X-XSRF-TOKEN 的标头或 HTTP 参数 _csrf 中读取它。这些默认值来自 AngularJS”。


推荐阅读