【问题标题】:How to resolve InvalidAuthenticityToken on Rails Stripe App如何解决 Rails Stripe 应用程序上的 InvalidAuthenticityToken
【发布时间】:2018-11-14 05:16:51
【问题描述】:

您好,我正在使用 Stripe 在我的 Rails 5 应用程序中实现结帐。结账过程将允许用户使用 Apple Pay 或 Google Pay 结账。我使用了 Stripe 文档中的示例 JS 代码来实现支付请求。我还将 X-CSRF-Token 添加到服务器的 xhr 发布请求的标头中:

...
fetch('/checkout', {
  method: 'POST',
  body: JSON.stringify({token: ev.token.id}),
  headers: {
    'content-type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
  }
})
...

在我收到的服务器的响应中:

ActionController::InvalidAuthenticityToken in CheckoutController#create

我正在使用 Devise 来保护结帐,并且我了解到您可以通过在控制器中添加以下内容来禁用真实性检查:

protect_from_forgery prepend: true

但是这会导致 302 重定向到 /users/sign_in

【问题讨论】:

    标签: ruby-on-rails devise stripe-payments fetch-api


    【解决方案1】:

    问题是你的请求没有经过身份验证,因为它是在没有cookies的情况下发送的,因为Fetch APIfetch默认不包含cookies。

    设置 credentials 选项以在请求中包含 cookie。

    fetch('/checkout', {
      // ...
      credentials: 'same-origin'  // or 'include' (see the link below)
    })
    

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-13
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 2016-11-21
      • 2020-02-22
      相关资源
      最近更新 更多