gpt4 book ai didi

json - 为 json post 请求获取 csrf token 到 Rails 应用程序

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

我一直在尝试使用 rest-client 来访问我编写的 Rails 应用程序。我编写了一个快速脚本来登录并发出发布请求。一切正常,但我确实必须解决这样一个事实,即如果您在 json 中请求表单,则不会提供真实性_ token 。我必须在其他获取真实性 token 中发出常规 html 请求,然后将其包含在我作为发布请求的一部分提交的 json 中。基本上我有一个快速的脏脚本,如下所示

private_resource = RestClient::Resource.new( 'https://mysite.com')

params = {:user => {:email => 'user@mysite.com', :password => 'please'}}
#log in
login_response = private_resource['users/sign_in'].post(params, :content_type => :json, :accept => :json)
#get cookie
cookie = login_response.cookies
#get json
json_response = private_resource['products/new'].get(:content_type => :json, :accept => :json, :cookies => cookie)
#another request that returns html form with authenticity token
response_with_token = private_resource['products/new'].get( :cookies => cookie)
#extract token
token = Nokogiri::XML(response_with_token).css('input[name=authenticity_token]').first.attr('value')
#update cookie
cookie = response_with_token.cookies
#populate form and insert token
form = JSON.parse(json_response)
form['name'] = "my product"
form['authenticity_token'] = token
#submit the request
private_resource['products'].post(form.to_json, {:cookies => cookie, :content_type => :json, :accept => :json})

可以选择关闭 json 请求的 CSRF 保护,但我宁愿不这样做。我可以走机械化路线或类似的路线,然后我不会担心 CSRF 的 json 请求,但我只是想玩玩用 rest-client 做这些事情

我想我只是想知道是否有一个原因为什么没有为 json 请求提供真实性_ token ,我还想知道是否有比我在这里采取的非常hacky 方法更好的方法来解决 token 问题

最佳答案

将以下代码放入您的应用程序 Controller :

def verified_request?
if request.content_type == "application/json"
true
else
super()
end
end

并使用 before_filter 调用此方法。

有关更多详细信息,请检查:
http://blog.technopathllc.com/2011/09/rails-31-csrf-token-authenticity-for.html

并在 rails 中检查此问题: https://github.com/rails/rails/issues/3041

关于json - 为 json post 请求获取 csrf token 到 Rails 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10413803/

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