How to get bearer token passed through header in rails?
Asked Answered
S

3

20

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?

Scheller answered 2/6, 2017 at 7:48 Comment(0)
G
41

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'
Gallicanism answered 2/6, 2017 at 8:42 Comment(0)
B
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.

Barefaced answered 4/7, 2017 at 22:32 Comment(0)
P
6

You could also use

request.headers['Authorization'].split(' ').last
Proctor answered 12/6, 2019 at 18:38 Comment(2)
it's bug prone because it will be throw exception if header is not given or not stringBeckon
@Beckon request.headers will always return an object that responds to [] (see api.rubyonrails.org/classes/ActionDispatch/… ; so, you could simple improve make it safer: request.headers['Authorization'].to_s.split(' ').lastBoyette

© 2022 - 2024 — McMap. All rights reserved.