【问题标题】:CSRF-token error when added OAuth2 to spring-boot将 OAuth2 添加到 spring-boot 时出现 CSRF-token 错误
【发布时间】:2018-02-17 19:54:01
【问题描述】:

我已将 OAuth2 添加到我的 spring-boot 应用程序中,到目前为止我只使用 google 作为登录名。登录部分工作正常,但当我发送 POST 请求时,我收到以下错误

{
    "timestamp": 1504901957320,
    "status": 403,
    "error": "Forbidden",
    "message": "Could not verify the provided CSRF token because your session was not found.",
    "path": "/compute"
}

现在我知道我可以在春季禁用 CSRF,但这不是最佳做法。 spring-boot 是自动设置 CSRF 令牌还是我必须添加一些东西才能使其工作。现在我不知道问题是否出在我没有添加令牌的角度代码发出请求时

let headers = new Headers();
headers.append("Content-Type", "application/json");

this.http.post("/compute", JSON.stringify(source), { headers }).subscribe((response: Response) => {
  if (response.ok) {
    this.mainpage.terminalComponent.logToTerminal(new Date(), response.text());
  }
}); 

或者我没有创建令牌并从后端设置它?

【问题讨论】:

  • headers 没有附加CSRF 令牌
  • 好吧!我刚开始使用 Angular,所以一切对我来说都是新的。如何获取令牌并将其附加到headers?顺便说一句,感谢您的快速回答! @Aravind

标签: spring angular rest spring-boot spring-security


【解决方案1】:

据此官方Spring Security and Angular JS tutorial。 Angular 内置了对 CSRF 的支持。

Angular 有基于 cookie 的 built in support for CSRF(它称之为“XSRF”)。

您可以在 Spring Boot 端使用自定义过滤器,将名为 XSRF-TOKEN 的 cookie 发送回 Angular。

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .httpBasic().and()
      .authorizeRequests()
        .antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll().anyRequest()
        .authenticated().and()
      .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
  }
}

有关详细信息,请阅读题为“CSRF 保护”的教程部分。

【讨论】:

  • Spring 有很好的 csrf 文档:检查 spring doc 对于角度指南,检查 angular doc 希望对您有所帮助...
猜你喜欢
  • 2015-06-11
  • 1970-01-01
  • 2018-03-10
  • 2021-12-05
  • 2017-08-31
  • 2022-12-02
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多