Rails chokes on the contents of this query due to protect_from_forgery

I am trying to just test my RESTful API with cURL. Using the following call:

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 '

This seems to work through the protect_from_forgery filter. I thought protected_from_forgery was excluded for HTTP requests like HTTP POST / PUT / DELETE? This is clearly aimed at the XML format.

If I pass the actual XML content, it works. But my users will send POST data as URLs. I know all the different ways I can turn off_from_forgery protection, but what is the correct way to solve it? I want to leave it so that when I have HTML forms and process format.html, I remember to include it again. I want users to be able to make HTTP POST requests to my XML-based API, although they are not bombarded by this.

+3
source share
1 answer

How about this?

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 rot:

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

Here 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>

+2
source

Source: https://habr.com/ru/post/1741627/


All Articles