使用 Rest Client Ruby Gem 的身份验证标头 [英] Authentication headers using Rest Client Ruby Gem

查看:57
本文介绍了使用 Rest Client Ruby Gem 的身份验证标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个基本的身份验证密钥,现在我正在尝试使用它.我尝试了几种不同的变体,但似乎没有一个在请求标头中显示授权.

I have already created a basic authentication key, now I am just trying to utilize it. I have tried a few different variations, but none seem to show Authorization in the request headers.

$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 添加身份验证标头的经验?

Unfortunately I am not finding a lot of info in the rdoc that can help me solve this. Does anyone have experience adding auth headers using the Rest Client gem?

推荐答案

对于 Basic Auth,您应该能够在创建资源时以明文形式设置用户和密码:

For Basic Auth, you should be able to set the user and password in plaintext when you create the resource:

resource = RestClient::Resource.new( 'http://example.com', 'user', 'password' )

但是如果你真的需要为每个请求直接设置头部:

But if you really need to set the header directly per request:

@response = resource.post( request_payload, :Authorization => $auth )

应该可以.如果没有,那么您可能设置了错误的 $auth.但是,我认为您只是错过了添加请求负载,因此它使用了您为所需参数提供的哈希值,而根本没有设置任何标头.

should work. If it does not, then you may have set $auth incorrectly. However, I think you just missed adding the request payload, so it was using the hash you supplied for that required param, and not setting any headers at all.

这是一个使用 get 的完整且有效的示例(我没有提供基本身份验证和 POST 的测试服务)

Here's a complete and working example using get (I don't have a test service available with Basic Auth and 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}"

注意:虽然这可行,但我建议您使用第一种也是最简单的方法,向构造函数提供用户和密码,除非您有充分的理由不这样做.

这篇关于使用 Rest Client Ruby Gem 的身份验证标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆