导轨阿贾克斯无法验证CSRF令牌真实性令牌、导轨、真实性、CSRF

2023-09-10 13:26:35 作者:孤街浪徒

在我的Rails应用我收到警告:无法验证CSRF令牌的真实性的一个ajax岗位的API。

应用/视图/布局/ application.html.haml 的

 !
%HTML
  %头
    = stylesheet_link_tag应用程序,:媒体=> 所有
    = javascript_include_tag应用程序
    = csrf_meta_tags
  %体
    =产量
 

阿贾克斯后的

  $阿贾克斯(网址:{url:#{card_credits_path}',
 键入:POST,
 beforeSend:功能(XHR){xhr.setRequestHeader(X-CSRF令牌,#{form_authenticity_token}')},
 数据类型:JSON,
 数据:{credit_uri:response.data.uri,
         电子邮件:$('#电子邮件:隐藏)VAL()。
         名称:$('名')VAL()。
       },
成功:函数(randomobject){
   了window.location ='/';
   },
错误:函数(){
   的console.log(卡的信息是错误的!);
   }
});
 
在游戏中开挂 谩骂将降低个人信用,你支持吗

解决方案

假设你已经设置令牌使用Rails的 csrf_meta_tag 标记的CSRF,请求的令牌将可在 CSRF令牌 meta标签:

 < META CONTENT =uniquetokenNAME =CSRF令牌/>
 

由于您使用jQuery,您可以令牌通过调用下面的值的 beforeSend 键传递到您的AJAX请求:

 函数(XHR){xhr.setRequestHeader(X-CSRF令牌',$('元[NAME =CSRF令牌])。ATTR(内容 ))}
 

In my rails app I'm getting "WARNING: Can't verify CSRF token authenticity" on an ajax post to an api.

app/views/layouts/application.html.haml :

!!!
%html
  %head
    = stylesheet_link_tag "application", :media => "all"
    = javascript_include_tag "application"
    = csrf_meta_tags
  %body
    = yield

ajax post :

$.ajax({ url: '#{card_credits_path}',
 type: 'POST',
 beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
 dataType: "json",
 data: { credit_uri: response.data.uri,
         email: $('#email:hidden').val(),
         name: $('.name').val()
       },
success: function(randomobject) {
   window.location = '/';
   },
error: function(){
   console.log("Card information is wrong!");
   }
});

解决方案

Assuming you've set the CSRF token using the Rails csrf_meta_tag tag, the request's token will be available in the csrf-token meta tag:

<meta content="u-n-i-q-u-e-t-o-k-e-n" name="csrf-token" />

Since you're using jQuery, you can pass the token to your AJAX request by invoking the following value for the beforeSend key:

function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}