Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bearer token passed through header in rails?

In my rails application I'm able to get the Token Authorization: Token token='aUthEnTicAtIonTokeN' passed in header of request with

authenticate_with_http_token do |token, options|
 @auth_token = token
end

but when I pass token as Authorization: Bearer token='aUthEnTicAtIonTokeN' getting token as nil above method.

how can i get bearer token passed through header in rails application?

like image 761
sat's Avatar asked Jun 02 '17 07:06

sat's


People also ask

How do you pass bearer token in header curl?

Sending the Bearer Token with a Curl POST request is similar to sending the Bearer Token with a Curl GET request. POST data is passed with the -d command-line option, and the authorization header and the bearer token are passed with the -H command-line option.

How do I send a bearer token in header insomnia?

Using a GUI app If you're using Insomnia, start by creating a new GET request (click the plus icon, or use keyboard command+N or control+N on Windows/Linux). In the “Auth” dropdown menu, select “Bearer Token”. Type in your access token in the “TOKEN” field, and type the word “Bearer” in the “PREFIX” field.


2 Answers

You could get the Bearer token with a method like:

def bearer_token
  pattern = /^Bearer /
  header  = request.headers['Authorization']
  header.gsub(pattern, '') if header && header.match(pattern)
end

Also, when setting the header it should be:

Authorization: Bearer 'aUthEnTicAtIonTokeN'
like image 188
Alex.U Avatar answered Oct 02 '22 10:10

Alex.U


Your method will work correctly as it is, you just need to use the correct quotes in the request.

Using single quotes ' doesn't work, where as double quotes " does.

For reference, rails handles tokens from the Authorization: header in any of the following formats with the authenticate_with_http_token method:

Bearer "token_goes_here"
Bearer token_goes_here
Bearer token="token_goes_here"
Bearer token=token_goes_here
Token token="token_goes_here"
Token token=token_goes_here
Token "token_goes_here"
Token token_goes_here

I'm sure this list is not exhaustive, but hopefully gives an idea of what is possible.

like image 33
pronoob Avatar answered Oct 02 '22 09:10

pronoob