Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication headers using 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 })

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?

like image 533
Josh Avatar asked Jan 02 '14 19:01

Josh


People also ask

What is authentication header in API?

An authentication header is required for all calls to the REST endpoint. The Authorization field in the HTTP header is used to pass user credentials. When authentication fails, the error code 401 (Unauthorized) is returned with additional information in the WWW-Authenticate header of the response.

What is RESTClient?

REST Client is a method or a tool to invoke a REST service API that is exposed for communication by any system or service provider. For example: if an API is exposed to get real time traffic information about a route from Google, the software/tool that invokes the Google traffic API is called the REST client.


Video Answer


1 Answers

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 )

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.

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}"

Note: Though this works, I recommend you use the first and simplest method of supplying user and password to the constructor unless you have good reason not to.

like image 55
Neil Slater Avatar answered Oct 29 '22 20:10

Neil Slater