ruby-on-rails – 由于protect_from_forgery,Rails会阻塞此请求的内容

我试图用cURL简单地测试我的RESTful API.使用以下调用:

curl -d "name=jimmy" -H "Content-Type: application/x-www-form-urlencoded" http://127.0.0.1:3000/people.xml -i

Rails虽然濒临死亡:

ActionController :: InvalidAuthenticityToken(ActionController :: InvalidAuthenticityToken):
  :8:在’同步’中

看起来它是通过protect_from_forgery过滤器运行的.我认为对于非HTML HTTP POST / PUT / DELETE类型请求,不包括protect_from_forgery?这显然是针对XML格式的.

如果我传递实际的XML内容,它就可以了.但我的用户将提交POST数据作为URL编码参数.我知道我可以通过各种方式禁用protect_from_forgery,但处理此问题的正确方法是什么?我想保留它,以便当我有基于HTML的表单并处理format.html时,我不会忘记重新启用它.我希望用户能够对我的基于XML的API发出HTTP POST请求,但不会受到轰炸.

最佳答案 走这条路怎么样?

在你的控制器中:

  skip_before_filter :verify_authenticity_token, :only => :api

      def api
        @callback = request.body.read
        if !@callback.blank?
          People.create :name => @callback
       end
      end

在routes.rb中:

  map.api '/api', :controller => "people", :action => "api"

然后卷曲:

curl -d "jimmy" http://localhost:3000/api -i

这就是我得到的:

HTTP/1.1 200 OK
Connection: close
Date: Wed, 21 Apr 2010 16:31:52 GMT
ETag: "1bafa7f069ba62f46577e0172a29b7cc"
Content-Type: text/html; charset=utf-8
X-Runtime: 141
Content-Length: 476
Set-Cookie: _tsearchtest_session=BAh7BjoPc2Vzc2lvbl9pZCIlNjJlOTViOGZhODc1NmU5NDg1MWUyYWQ3YWQ0NzFiYjU%3D--651c3bfcbb0f180c72653379678d410711ead2eb; path=/; HttpOnly
Cache-Control: private, max-age=0, must-revalidate

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>People: api</title>
  <link href="/stylesheets/scaffold.css?1271863770" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>

<p style="color: green"></p>
点赞