I'm trying to simply test my RESTful API with cURL. Using the following invoca开发者_StackOverflow社区tion:
curl -d "name=jimmy" -H "Content-Type: application/x-www-form-urlencoded" http://127.0.0.1:3000/people.xml -i
Rails is dying though:
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): :8:in `synchronize'
Looks like it's running this through a protect_from_forgery filter. I thought protect_from_forgery is excluded for non-HTML HTTP POST/PUT/DELETE type requests? This is clearly targeting the XML format.
If I pass actual XML content, it works. But my users will be submitting POST data as URL encoded parameters. I know all the various ways I can disable protect_from_forgery but what's the proper way of handling this? I want to leave it on so that when I do have HTML based forms and handle format.html, I don't forget to re-enable it for then. I want users to be able to make HTTP POST requests to my XML-based API though and not get bombarded with this.
How about going this way?
In your controller:
skip_before_filter :verify_authenticity_token, :only => :api
def api
@callback = request.body.read
if !@callback.blank?
People.create :name => @callback
end
end
In routes.rb:
map.api '/api', :controller => "people", :action => "api"
Then curl:
curl -d "jimmy" http://localhost:3000/api -i
This is what i get:
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>
精彩评论