出于某种原因,当我使用 json 或 xml 向我的应用程序发出发布请求时,我得到了一个 InvalidAuthenticityToken。我的理解是 rails 应该只对 html 或 js 请求需要真实性 token ,因此我不应该遇到这个错误。到目前为止,我发现的唯一解决方案是对我想通过 API 访问的任何操作禁用protect_from_forgery,但由于显而易见的原因,这并不理想。想法?
def create
respond_to do |format|
format.html
format.json{
render :json => Object.create(:user => @current_user, :foo => params[:foo], :bar => params[:bar])
}
format.xml{
render :xml => Object.create(:user => @current_user, :foo => params[:foo], :bar => params[:bar])
}
end
end
每当我将请求传递给操作时,这就是我在日志中得到的信息:
Processing FooController#create to json (for 127.0.0.1 at 2009-08-07 11:52:33) [POST]
Parameters: {"foo"=>"1", "api_key"=>"44a895ca30e95a3206f961fcd56011d364dff78e", "bar"=>"202"}
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
thin (1.2.2) lib/thin/connection.rb:76:in `pre_process'
thin (1.2.2) lib/thin/connection.rb:74:in `catch'
thin (1.2.2) lib/thin/connection.rb:74:in `pre_process'
thin (1.2.2) lib/thin/connection.rb:57:in `process'
thin (1.2.2) lib/thin/connection.rb:42:in `receive_data'
eventmachine (0.12.8) lib/eventmachine.rb:242:in `run_machine'
eventmachine (0.12.8) lib/eventmachine.rb:242:in `run'
thin (1.2.2) lib/thin/backends/base.rb:57:in `start'
thin (1.2.2) lib/thin/server.rb:156:in `start'
thin (1.2.2) lib/thin/controllers/controller.rb:80:in `start'
thin (1.2.2) lib/thin/runner.rb:174:in `send'
thin (1.2.2) lib/thin/runner.rb:174:in `run_command'
thin (1.2.2) lib/thin/runner.rb:140:in `run!'
thin (1.2.2) bin/thin:6
/opt/local/bin/thin:19:in `load'
/opt/local/bin/thin:19
请您参考如下方法:
与 protect_from_forgery
启用后,Rails 需要任何非 GET 请求的真实性 token 。 Rails 会自动在使用表单助手创建的表单或使用 AJAX 助手创建的链接中包含真实性标记——因此在正常情况下,您不必考虑它。
如果您没有使用内置的 Rails 表单或 AJAX 帮助程序(也许您正在执行不引人注目的 JS 或使用 JS MVC 框架),则您必须自己在客户端设置 token 并将其与您的提交 POST 请求时的数据。您可以在 <head>
中放置这样的一行您的布局:
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
然后您的 AJAX 函数会将 token 与您的其他数据一起发布(例如 jQuery):
$.post(url, {
id: theId,
authenticity_token: window._token
});