无法验证 CSRF 令牌的真实性 Rails/React

IT技术 ruby-on-rails reactjs csrf protect-from-forgery
2021-05-04 10:28:26

我的 rails 应用程序中有一个 react 组件,我试图在其中fetch()POST发送到托管在本地主机上的 rails 应用程序,这给了我错误:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

我正在使用设计 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 令牌并通过表单发送它以使其通过?
理想情况下,我只想通过标头发送它,但我不知道如何访问令牌。

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,所以不太确定确切的语法,但这应该有助于指导你。

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

<% 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);

我在使用rails 5.2时也遇到了同样的问题,我能够通过添加来解决这个问题

protect_from_forgery with: :null_sessionapplication_controller.rb 我从这里得到这个,请参考这个