反应 + springboot csrf

Posted

技术标签:

【中文标题】反应 + springboot csrf【英文标题】:React + springboot csrf 【发布时间】:2019-06-18 02:37:23 【问题描述】:

我在 springboot 项目中有一个 react 应用程序,react 应用程序使用 rest 调用获取/设置内容。实际上我已经在配置适配器.csrf().disable() 中禁用了 csrf,但我想管理这个。 如何在 react 和 springboot 之间处理 csrf 令牌?

我认为我应该通过我的 axios 调用传递令牌,但我如何得到它?

谢谢

【问题讨论】:

有一个很好的例子,你可以查看developer.okta.com/blog/2018/07/19/… 【参考方案1】:

上面的答案我认为它使用了旧的 spring 安全版本。有一个简单的方法。对于springboot后端,你可以这样做

.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

对于反应,您可以按照该答案的方式进行操作,但不要忘记使用 <CookiesProvider> 来总结您返回的内容

或者您可以从 document.cookie 中获取令牌。应该有一对以 XSRF-TOKEN=

开头

而且 csrf 不应该应用于 GET 方法。

【讨论】:

感谢您填写一些额外的信息!这对我很有帮助。 我能知道什么版本的 Spring Security 与您的源代码兼容吗? @wonsuc 我不确定,但我正在使用 org.springframework.security 5.1.5【参考方案2】:

您需要将CSRF-TOKEN 保存到cookie 中并与请求头一起发回。

SecurityConfig 类。

启用 csrftokenrepsitory

         .csrf().csrfTokenRepository(csrfTokenRepository()).and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class).addFilterAfter(new XSSFilter(), CsrfFilter.class);

添加 csrfTokenRepository

       private CsrfTokenRepository csrfTokenRepository() 
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName(X_CSRF_TOKEN);
    return repository;

在 react 中,您可以从 cookie 访问令牌。

    csrfToken=  cookies.get('XSRF-TOKEN');

在标头中按如下方式发送。

     headers: 
    'X-XSRF-TOKEN': this.csrfToken,
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  ,

https://github.com/supun/okta-spring-boot-react-crud-example/blob/master/src/main/java/com/okta/developer/jugtours/config/SecurityConfiguration.java

【讨论】:

实际将csrf 令牌保存到cookie 的部分是什么? Spring Security 是否管理此过程?还是我应该从前端层手动保存令牌? @wonsuc 是的。它是通过弹簧安全处理的。无需在前端保存。 完美。谢谢!

以上是关于反应 + springboot csrf的主要内容,如果未能解决你的问题,请参考以下文章

如何使用后端的 JWT 实用程序从前端验证 JWT? (反应+ Springboot)

Eclipse上运行Springboot项目突然JRebel不启动没反应了

Spring Boot 2 反应式 webflux

Spring Boot 反应式和 mongodb '命令插入需要身份验证'

Maven 反应器:使用 Spring Boot 启动器 pom 的 pom

使用 @EnableResourceServer 支持 Spring Boot 反应式 (webflux)