【问题标题】:Can't verify CSRF token authenticity Rails/React无法验证 CSRF 令牌的真实性 Rails/React
【发布时间】:2019-07-15 10:12:50
【问题描述】:

我在我的 rails 应用中有一个 react 组件,我正在尝试使用 fetch()POST 发送到托管在 localhost 上的 rails 应用,这给了我错误:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

我正在使用 devise gem 来处理 user/registrationslogins

我已尝试删除protect_from_forgery with: :exception

这是我获取的代码,

this.state.ids.sub_id});
  fetch(POST_PATH, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: body  
  }).then(res => res.json()).then(console.log);

如何获取 csrf 令牌并通过表单发送它以使其通过?
理想情况下,我只想通过标头发送它,但我不知道如何访问令牌。

【问题讨论】:

    标签: ruby-on-rails reactjs csrf protect-from-forgery


    【解决方案1】:

    我在使用 rails 5.2 时也遇到了同样的问题,我可以通过添加

    来解决这个问题

    protect_from_forgery with: :null_session in application_controller.rb i got this from here,please refer this

    【讨论】:

    • 这看起来像一个安全风险不是吗?
    • @SamuelFaure 我不是这方面的专家,也许你是对的,请参考随附的链接
    【解决方案2】:

    谢谢!我最终将此作为一个可行的解决方案: 在呈现我的反应组件的视图中

    <% csrf_token = form_authenticity_token %>
    
    <%= react_component('ExerciseDisplay', {
      program: @program.subprograms.first.exercises, ids: {sub_id: @program.subprograms.first.id, team_id: @team.id, token: csrf_token}
    }) %>
    

    我将令牌传递给 state,然后通过 fetch 访问它:

      fetch(POST_PATH, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': this.state.ids.token
          },
          body: body  
    }).then(res => res.json()).then(console.log);
    

    【讨论】:

      【解决方案3】:

      如果您只是在 Rails 视图中嵌入一个 React 组件,最简单的方法是从 Rails 视图中检索 csrf 令牌,然后将其作为标头传递给您的 fetch api 调用。

      您可以通过以下方式获取 csrf 令牌:

      const csrf = document.querySelector("meta[name='csrf-token']").getAttribute("content");
      

      然后你只需在 fetch 调用中将其作为标头传递: ... headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf }, ...

      我通常不使用 fetch,所以不太确定确切的语法,但这应该有助于指导您。

      【讨论】:

      • 但是他们现在在 Rails 5 及更高版本中没有执行 csrf 令牌吗?这仍然适用吗?
      猜你喜欢
      • 2017-07-15
      • 2015-07-24
      • 2014-06-16
      • 2012-05-08
      • 2015-12-29
      • 2023-03-26
      • 2016-09-17
      • 2012-12-11
      • 2014-07-04
      相关资源
      最近更新 更多