使用Rest Client Ruby Gem的身份validation标头
我已经创建了一个基本的身份validation密钥,现在我只是想利用它。 我尝试了一些不同的变体,但似乎都没有在请求标头中显示授权。
$auth = 'Basic cmFtZXNoQHVzYW1hLmNvbTpyYW1lc2h1JEBtcA==' @response = resource.post('Authorization' => $auth) nor @response = resource.post(:authorization => $auth) nor @response = resource.post(:Authorization => $auth) nor @response = resource.post(:content_type => :json, :accept => :json, :headers => { 'Authorization:' => $auth })
不幸的是,我没有在rdoc中找到很多可以帮助我解决这个问题的信息。 有没有人有使用Rest Client gem添加auth标头的经验?
对于Basic Auth,您应该能够在创建资源时以纯文本格式设置用户和密码:
resource = RestClient::Resource.new( 'http://example.com', 'user', 'password' )
但是,如果您确实需要根据请求直接设置标头:
@response = resource.post( request_payload, :Authorization => $auth )
应该管用。 如果没有,那么您可能错误地设置了$auth
。 但是,我认为您只是错过了添加请求有效负载,因此它使用了您为该必需参数提供的哈希,而根本没有设置任何标头。
这是一个使用get
的完整且有效的示例(我没有Basic Auth和POST提供的测试服务)
require 'rest-client' require 'base64' $auth = 'Basic ' + Base64.encode64( 'user:passwd' ).chomp $url = 'http://httpbin.org/basic-auth/user/passwd' @resource = RestClient::Resource.new( $url ) @response = @resource.get( :Authorization => $auth ) # => "{\n \"authenticated\": true,\n \"user\": \"user\"\n}"
注意:虽然这有效,但我建议您使用第一种也是最简单的方法为构造函数提供用户和密码,除非您有充分的理由不这样做。
如果您不想使用RestClient::Resource
,则可以在请求中包含基本身份validation,如下所示:
RestClient::Request.execute method: :get, url: url, user: 'username', password: 'secret'
诀窍是不使用RestClient.get
(或.post
, .put
等)方法,因为您在其中传递的所有选项都用作标题。
我刚刚在这里写了一篇快速的文章: https : //www.krautcomputing.com/blog/2015/06/21/how-to-use-basic-authentication-with-the-ruby-rest-client-gem /
即使我没有有效载荷发送,我试图发送一个没有。 这最终成了原因。 所以我包括:
json_str = '' @response = resource.post(json_str, :content_type => :json, :accept => :json, :Authorization => $auth)
这很有效。