我正在尋找從curl POST到Rails應用程序。我已經能夠驗證並獲得200響應。但是,當我嘗試POST一些數據失敗。問題與使用捲曲驗證郵政的Rails
我的控制器代碼:
class TestApiController < ApplicationController
before_action :authenticate
def server_reporter
puts params
end
protected
def authenticate
authenticate_or_request_with_http_token do |token, options|
# User.find_by(auth_token: token)
token == '1234'
end
end
end
當我運行這個
curl -v localhost:3000/test_api/server_reporter -IH "Authorization: Token token=1234"
我得到
Started HEAD "/test_api/server_reporter" for ::1 at 2016-10-10 11:27:19 +0200
Processing by TestApiController#server_reporter as */*
{"controller"=>"test_api", "action"=>"server_reporter"}
Rendered test_api/server_reporter.html.erb within layouts/application (0.2ms)
Completed 200 OK in 221ms (Views: 220.2ms | ActiveRecord: 0.0ms)```
當我嘗試
curl -v localhost:3000/test_api/server_reporter -X POST -H "Authorization: Token token=1234" -H "Content-Type: application/json" -d '{"server": {"name": "Asterix"}}'
我在Rails控制檯中得到以下內容。
Started POST "/test_api/server_reporter" for ::1 at 2016-10-10 15:59:36 +0200
Processing by TestApiController#server_reporter as */*
Parameters: {"server"=>{"name"=>"Asterix"}, "test_api"=>{"server"=>{"name"=>"Asterix"}}}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken:
編輯:添加curl
響應。
$ curl -v localhost:3000/test_api/server_reporter -X POST -H "Authorization: Token token=1234" -H "Content-Type: application/json" -d '{"server": {"name": "Asterix"}}'
* Trying ::1...
* Connected to localhost (::1) port 3000 (#0)
> POST /test_api/server_reporter HTTP/1.1
> Host: localhost:3000
> User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
> Accept: */*
> Referer:
> Authorization: Token token=1234
> Content-Type: application/json
> Content-Length: 31
>
* upload completely sent off: 31 out of 31 bytes
< HTTP/1.1 422 Unprocessable Entity
< Content-Type: text/plain; charset=utf-8
< X-Meta-Request-Version: 0.4.0
< X-Request-Id: a13faa8e-20b4-4107-ba5f-1c6fde1f8ce1
< X-Runtime: 0.077414
< Set-Cookie: __profilin=p%3Dt; path=/
< Connection: close
< Server: thin
<
ActionController::InvalidAuthenticityToken at /test_api/server_reporter
=======================================================================
> ActionController::InvalidAuthenticityToken
不就是繞過認證? – davidt
更新了我的答案。請看看它。 – Jayaprakash
太好了,謝謝你的工作。剛剛檢查過,現在也是有道理的。 – davidt