sonnyhe2002
sonnyhe2002

Reputation: 2121

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?

Upvotes: 5

Views: 19029

Answers (3)

Tilo
Tilo

Reputation: 33742

The accepted answer does not work.

In Rails 4 it should be request.authorization not request['authorization']

Upvotes: 0

Darren Weber
Darren Weber

Reputation: 1674

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

Upvotes: 1

Maurício Linhares
Maurício Linhares

Reputation: 40333

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.

Upvotes: 18

Related Questions