18

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?

sat's
  • 303
  • 1
  • 2
  • 7

3 Answers3

39

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'
Alex.U
  • 1,631
  • 2
  • 16
  • 26
9

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.

pronoob
  • 811
  • 1
  • 10
  • 20
5

You could also use

request.headers['Authorization'].split(' ').last
Scott Davidson
  • 995
  • 1
  • 9
  • 12
  • it's bug prone because it will be throw exception if header is not given or not string – Nozim Jan 02 '23 at 19:04
  • @Nozim request.headers will always return an object that responds to `[]` (see https://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-headers ; so, you could simple improve make it safer: `request.headers['Authorization'].to_s.split(' ').last` – sandre89 Sep 02 '23 at 02:25