机械化帖子给我无法验证CSRF令牌的真实性

时间:2014-02-10 11:55:38

标签: ruby-on-rails mechanize 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

1 个答案:

答案 0 :(得分:0)

你可以做几件事。

  1. 仅在过滤器之前跳过某些操作(使用:only参数)。
  2. 添加一个额外步骤:转到温度表单并通过此表单上的按钮发布。
  3. 转到温度表格,从中提取CSRF令牌并使用这些令牌进行POST。
  4. 但是,正确的方法是分离JSON API和html表单的安全措施。您可以实现某种基于密钥的授权来访问API,或者使用已经实现的解决方案(例如Grape)。