Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do Rails Basic Authorization with RestClient?

I am trying to post a request to a REST service (HP ALM 11 REST API fwiw) using rest-client and keep getting the Unauthorized response. Could be I am not following the docs right but also I am not sure I am doing the headers properly. So far my googling for RestClient has been fruitless. Any help would be appreciated:

Code:

@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

Based on this SO question I also tried the following without success:

@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

Documentation:

Client sends a valid Basic Authentication header to the authentication point.

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

Server validates the Basic authentication headers, creates a new LW-SSO token and returns it as LWSSO_COOKIE_KEY.

like image 308
ScottJShea Avatar asked Feb 08 '12 20:02

ScottJShea


1 Answers

Okay... so first it helps if I go to the right URL:

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

Which should read:

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

Secondly, it helps if I read the docs for RestClient rather than just look at the readme. The example under Instance Method Details helped a lot.

My code now looks like:

@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

EDIT:

Wow I really over-thought this. I could have gone with:

response = RestClient.get "http://#{@user_name}:#{@user_password}@alm_url/qcbin/authentication-point/authenticate"
like image 64
ScottJShea Avatar answered Sep 23 '22 08:09

ScottJShea