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

查看:104
本文介绍了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类方法),当我尝试使用curl创建记录时,我开始执行create动作,并且开始出现ActionController::InvalidAuthenticityToken异常.

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 "<my data here>"设置了数据,但是仍然没有运气.

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

路轨4 :

def handle_unverified_request
  forgery_protection_strategy.new(self).handle_unverified_request
end

哪个会调用 查看全文

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