[英]mechanize post gives me Can't verify CSRF token authenticity
我正在嘗試創建一個腳本,該腳本會將遠程設備的溫度讀數發布到我的網站。 我目前正在本地對其進行測試,並且嘗試發布時遇到了此錯誤:
運行腳本時出錯
/home/map7/.rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/mechanize-2.7.3/lib/mechanize/http/agent.rb:720:in `
response_authenticate': 401 => Net::HTTPUnauthorized for http://localhost:3000/temperatures.json -- WWW-Authenticate header missing in response (Mechanize::UnauthorizedError)
from /home/map7/.rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/mechanize-2.7.3/lib/mechanize/http/agent.rb:302:in `fetch'
from /home/map7/.rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/mechanize-2.7.3/lib/mechanize.rb:526:in `request_with_entity'
from /home/map7/.rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/mechanize-2.7.3/lib/mechanize.rb:480:in `post'
from ./temperature_upload.rb:34:in `<main>'
Rails日志中的錯誤
Started POST "/temperatures.json" for 127.0.0.1 at 2014-02-10 22:46:47 +1100
Processing by TemperaturesController#create as JSON
Parameters: {"temperature"=>{"temperature"=>"29"}}
WARNING: Can't verify CSRF token authenticity
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
(0.0ms) begin transaction
(0.0ms) commit transaction
Completed 401 Unauthorized in 2ms
我的劇本
#!/usr/bin/env ruby
#
# EG: http://mechanize.rubyforge.org/GUIDE_rdoc.html
require 'mechanize'
HOST="http://localhost:3000"
# Setup Mechanize
agent = Mechanize.new
page =agent.get('http://localhost:3000/users/sign_in')
# Get user details
begin
string = IO.read("#{ENV['HOME']}/.details")
rescue
exit
end
json=JSON.parse(string)
# Login to my winesite
login_form = page.form("login")
login_form.field_with(type: "email").value = json["email"]
login_form.field_with(type: "password").value = json["password"]
page = agent.submit(login_form)
headers = { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
agent.post("#{HOST}/temperatures.json", '{"temperature":{"temperature": "29"}}', headers)
如果我將以下內容添加到我的控制器中,它將發布。 有沒有一種方法可以發布而不必禁用此功能:
skip_before_filter :verify_authenticity_token
您可以做幾件事。
:only
參數)。 但是,正確的方法是將JSON API和html表單的安全措施分開。 您可以實現某種基於密鑰的授權來訪問API,或者使用已經實現的解決方案(例如Grape )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.