2014-02-10 34 views
0

我想創建一個腳本,將溫度讀數從遠程設備發佈到我的網站。我在本地測試它現在,我嘗試後,當運行到這個錯誤:在軌日誌機械化後發給我無法驗證CSRF令牌的真實性

錯誤運行腳本時

/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>' 

錯誤

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 

回答

0

有幾件事你可以做。

  1. 只在某些操作的過濾器之前跳過(使用:only參數)。
  2. 添加額外的步驟:轉到溫度表單並通過此表單上的按鈕發佈。
  3. 轉到溫度表單,使用這些令牌從中提取CSRF令牌和POST。

但是,正確的做法是將JSON API和html表單的安全措施分開。您可以實施某種基於密鑰的授權來訪問API,或使用已實施的解決方案(例如Grape)。

相關問題