ruby-on-rails 无法验证CSRF令牌真实性Rails/React

bq9c1y66  于 2023-02-14  发布在  Ruby
关注(0)|答案(4)|浏览(105)

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

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

我使用devise gem来处理user/registrationslogins
我已尝试删除protect_from_forgery with: :exception
下面是我的fetch代码,

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令牌并通过表单发送它以便它通过?
理想情况下,我希望只是通过头部发送它,但我不知道如何访问令牌。

83qze16e

83qze16e1#

如果只是在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,所以不太清楚确切的语法,但这应该有助于指导您。

r1wp621o

r1wp621o2#

谢谢!我最终得到了这个作为工作解决方案:在渲染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);
tuwxkamq

tuwxkamq3#

form元素中,添加authenticity_token

<input type="hidden" name="authenticity_token" value={csrf}/>

按如下设置值:

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

7d7tgy0s4#

我在使用rails 5.2时也遇到了同样的问题,我可以通过添加以下内容来解决这个问题

应用程序控制器.rb中的protect_from_forgery with: :null_sessioni got this from here,please refer this

相关问题