Rails 4 真实性令牌 [英] Rails 4 Authenticity Token

查看:28
本文介绍了Rails 4 真实性令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遇到一些真实性令牌问题时,我正在开发一个新的 Rails 4 应用程序(在 Ruby 2.0.0-p0 上).

I was working on a new Rails 4 app (on Ruby 2.0.0-p0) when I ran into some authenticity token problems.

在编写响应 json 的控制器时(使用 respond_to 类方法),我得到了 create 操作,我开始获取 ActionController::InvalidAuthenticityToken<当我尝试使用 curl 创建记录时的/code> 异常.

While writing a controller that responds to json (using the respond_to class method), I got to the create action I started getting ActionController::InvalidAuthenticityToken exceptions when I tried to create a record using curl.

我确保我设置了 -H "Content-Type: application/json" 并且我用 -d "" 设置了数据但是仍然没有运气.

I made sure I set -H "Content-Type: application/json" and I set the data with -d "<my data here>" but still no luck.

我尝试使用 Rails 3.2(在 Ruby 1.9.3 上)编写相同的控制器,但我没有遇到任何真实性令牌问题.我四处搜索,发现 Rails 4 中的真实性令牌发生了一些变化.据我所知,它们不再自动插入表单了?我想这在某种程度上影响了非 HTML 内容类型.

I tried writing the same controller using Rails 3.2 (on Ruby 1.9.3) and I got no authenticity token problems whatsoever. I searched around and I saw that there were some changes with authenticity tokens in Rails 4. From what I understand, they are no longer automatically inserted in forms anymore? I suppose this is somehow affecting non-HTML content types.

有什么方法可以解决这个问题,而不必请求 HTML 表单、获取真实性令牌,然后使用该令牌发出另一个请求?还是我完全遗漏了一些非常明显的东西?

Is there any way to get around this without having to request a HTML form, snatching the authenticity token, then making another request with that token? Or am I completely missing something that's completely obvious?

我只是尝试使用脚手架在一个新的 Rails 4 应用程序中创建一个新记录,但没有进行任何更改,但我遇到了同样的问题,所以我想这不是我做的.

I just tried creating a new record in a new Rails 4 app using a scaffold without changing anything and I'm running into the same problem so I guess it's not something I did.

推荐答案

我想我刚刚想通了.我更改了(新的)默认值

I think I just figured it out. I changed the (new) default

protect_from_forgery with: :exception

protect_from_forgery with: :null_session

根据 ApplicationController 中的注释.

# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.

您可以通过查看 request_forgery_protecton.rb 的源代码,或更具体地说,以下几行来了解差异:

You can see the difference by looking at the source for request_forgery_protecton.rb, or, more specifically, the following lines:

Rails 中3.2:

# This is the method that defines the application behavior when a request is found to be unverified.
# By default, Rails resets the session when it finds an unverified request.
def handle_unverified_request
  reset_session
end

Rails 4:

def handle_unverified_request
  forgery_protection_strategy.new(self).handle_unverified_request
end

这将调用 以下:

def handle_unverified_request
  raise ActionController::InvalidAuthenticityToken
end

这篇关于Rails 4 真实性令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆