Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set authentication token in http header

I have been following the railscast on how to set authentication tokens http://railscasts.com/episodes/352-securing-an-api?view=asciicast

I have setup my app very well and it uses the authenticate_or_request_with_http_token method to get the token.

My problem is that I have a next app that needs to set the token in the header. Something like:

uri = URI.parse(full_url)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request['HTTP_AUTHORIZATION'] = 'this_is_a_test_key'
response = http.request(request)

The above code is getting an access denied. I know it is easy to set custom ones like X-CUSTOM-TOKEN, but how do I set the default one?

like image 514
sonnyhe2002 Avatar asked Aug 25 '14 07:08

sonnyhe2002


People also ask

How do I add auth token in header?

The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.

How do I set basic authentication in HTTP header?

Basic Auth:The client sends HTTP requests with the Authorization header that contains the word Basic, followed by a space and a base64-encoded(non-encrypted) string username: password. For example, to authorize as username / Pa$$w0rd the client would send. Note: Base64 encoding does not mean encryption or hashing!

How do you pass authentication information in the request header?

It is indeed not possible to pass the username and password via query parameters in standard HTTP auth. Instead, you use a special URL format, like this: http://username:[email protected]/ -- this sends the credentials in the standard HTTP "Authorization" header.

Does HTTP headers support authentication?

HTTP supports the use of several authentication mechanisms to control access to pages and other resources. These mechanisms are all based around the use of the 401 status code and the WWW-Authenticate response header. The client sends the user name and password as unencrypted base64 encoded text.


2 Answers

The header name isn't HTTP_AUTHORIZATION and you have to set it like this set it as:

request['authorization'] = "Token token=#{token}"

To be able to use the authenticate_or_request_with_http_token method.

like image 178
Maurício Linhares Avatar answered Sep 20 '22 19:09

Maurício Linhares


Look at the ActionController::HttpAuthentication module, e.g.

user = 'whatever'
pass = 'you-like'
auth = ActionController::HttpAuthentication::Basic.encode_credentials(user, pass)
request.headers['Authorization'] = auth

Similarly for a token, e.g.

token = 'whatever-it-is'
auth = ActionController::HttpAuthentication::Token.encode_credentials(token)
request.headers['Authorization'] = auth
like image 28
Darren Weber Avatar answered Sep 18 '22 19:09

Darren Weber