如何使用RestClient进行Rails基本授权?

10

我正在尝试使用rest-client向REST服务(具体来说是HP ALM 11 REST API)发送请求,但一直收到未经授权的响应。可能是因为我没有正确遵循文档,但我也不确定自己是否正确设置了头部信息。到目前为止,我在搜索RestClient方面并没有取得任何成果。非常感谢您提供的任何帮助:

代码:

@alm_url       = "http://alm_url/qcbin/"
@user_name     = "username"
@user_password = "password"

authentication_url = @alm_url + "rest/is-authenticate"
resource = RestClient::Resource.new authentication_url
resource.head :Authorization => Base64.encode64(@user_name) + ":" + Base64.encode64(@user_password)
response = resource.get


#response = RestClient.get authentication_url, :authorization => @username, @user_password
Rails.logger.debug response.inspect

根据这个SO问题,我也尝试了以下内容,但没有成功:

@alm_url       = "http://alm_url/qcbin/"
@user_name     = "username"
@user_password = "password"

authentication_url = @alm_url + "rest/is-authenticate"
resource = RestClient::Resource.new authentication_url, {:user => @user_name, :password => @user_password}
response = resource.get


#response = RestClient.get authentication_url, :authorization => @username, @user_password
Rails.logger.debug response.inspect

文档:

客户端向认证点发送有效的基本身份验证头。

GET /qcbin/authentication-point/authenticate Authorization: Basic ABCDE123

服务器验证基本身份验证头,创建一个新的LW-SSO令牌,并将其作为LWSSO_COOKIE_KEY返回。

1个回答

9

好的...首先,如果我访问正确的URL会有所帮助:

authentication_url = @alm_url + "rest/is-authenticate"

这应该是这样写的:

authentication_url = @alm_url + "authentication-point/authenticate"

其次,如果我阅读RestClient的文档而不仅仅是查看readme,这将有所帮助。在实例方法详情下的示例非常有用。

我的代码现在看起来像:

@alm_url       = "http://alm_url/qcbin/"
@user_name     = "username"
@user_password = "password"

authentication_url = @alm_url + "authentication-point/authenticate"
resource = RestClient::Resource.new(authentication_url, @user_name, @user_password)
response = resource.get

Rails.logger.debug response.inspect

编辑:

哇,我真的想太多了。我本来可以用以下简单明了的方法解决:

response = RestClient.get "http://#{@user_name}:#{@user_password}@alm_url/qcbin/authentication-point/authenticate"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接