4

请帮助 Rails 中的新手 :) 我在课堂protect_from_forgery上没有任何属性的调用(默认情况下给出) 。ApplicationController

基本上这里的代码:

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery
  helper_method :current_user_session, :current_user
  filter_parameter_logging :password, :password_confirmation

我认为它应该做的是:它应该防止任何没有正确的 POST 请求authenticity_token。但是当我像下面这样使用 jQuery 发送 post 请求时,它工作正常(在数据库中执行了更新语句)!

$.post($(this).attr("href"), { _method: "PUT", data: { test: true } });

我在控制台中看到authenticity_token发送的参数中没有,但请求仍然被认为是有效的。这是为什么?

UPD 在 config/environments/development.rb 中找到配置设置

config.action_controller.consider_all_requests_local = true

由于 DEV 环境和本地请求,这些 jQuery post 请求是可以的。

4

2 回答 2

2

There is nothing wrong with your code as long as the request $.post($(this).attr("href"), { _method: "PUT", data: { test: true } }); is executed from within the app itself. If you had another app running elsewhere, say for example on localhost:3001, and you sent a post from there then it won't work. Infact if you are on firefox > 3.0 it has an early implementation of cross site xhr too. For example you can send a POST from any other site (but this works provided protect_from_forgery is turned off!). The reason why auth token is not necessary for xhr is that cross site xhr is disabled. So it is safe to use xhr without providing auth token. If you try from any where else other than your app, i am sure it will raise an exception asking for an auth token. Also you should have a crossdomain.xml defined to prevent access from outside sources.

Try doing this: curl -X -d url_endpoint_of_your_app. See if you get a 200 response code. If you do then there is something fishy.

于 2010-04-28T00:01:48.800 回答
-1

也许是个愚蠢的问题:您确定要继承 ApplicationController 吗?你的路线图是什么样的?什么版本的 Rails(只是为了清楚起见)?

您是否验证了来自 jQuery 的调用实际上是 POST 而不是 GET?(我知道,这似乎很明显)。Rails 只会对非 GET 请求执行保护。

此外,发出的请求的内容类型是什么。根据文档, Rails 也只会在HTML/Javascript 请求时执行保护。

于 2010-04-27T21:22:04.710 回答