gpt4 book ai didi

ruby-on-rails - Mechanize 帖子让我无法验证 CSRF token 的真实性

转载 作者:行者123 更新时间:2023-12-04 16:22:07 24 4
gpt4 key购买 nike

我正在尝试创建一个脚本,它将温度读数从远程设备发布到我的网站。我现在正在本地测试它,并且在尝试发布时遇到了这个错误:

运行脚本时出错

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

如果我将以下内容添加到我的 Controller 中,它就会发布。有没有一种无需禁用即可发布的方法:
skip_before_filter :verify_authenticity_token

最佳答案

您可以做几件事。

  • 仅针对某些操作跳过过滤器之前(使用 :only 参数)。
  • 添加一个额外的步骤:转到温度表格并通过此表格上的按钮发布。
  • 转到温度表单,从中提取 CSRF token 并使用这些 token 进行 POST。

  • 但是,正确的做法是将 JSON API 和 html 表单的安全措施分开。您可以实现某种基于 key 的授权来访问 API,或使用已实现的解决方案(例如 Grape )。

    关于ruby-on-rails - Mechanize 帖子让我无法验证 CSRF token 的真实性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21676560/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com