ruby-on-rails - rails - 用于 json/xml 请求的 InvalidAuthenticityToken

标签 ruby-on-rails json restful-authentication

出于某种原因,当我使用 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
});

关于ruby-on-rails - rails - 用于 json/xml 请求的 InvalidAuthenticityToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1245618/

相关文章:

android - 需要帮助使用 Google Oauth 和 Android 配置 Django Rest API

java - Spring 安全 : AuthenticationProcessingFilter is called twice

iphone - WIF 是保护 iPhone 的 WCF 4.0 Restful 服务的好选择吗

jquery - 如何防止 Rails 中的 Enter 键提交

php - 匹配 MySQL JSON 列的全部内容

php - 可更改的自定义 JSON Ajax 循环

php - 解析 JSON 数组 PHP - 字符串和 float

sql - Rails Model.find() 不返回信息(返回散列)

ruby-on-rails - 多态关联和嵌套属性

ruby-on-rails - sqlite3 文件添加到 .gitignore 但仍在修改列表中?