在我的rails应用程序中,我能够通过
获取在请求标头中传递的令牌Authorization: Token token='aUthEnTicAtIonTokeN'
authenticate_with_http_token do |token, options|
@auth_token = token
end
但当我将令牌作为Authorization: Bearer token='aUthEnTicAtIonTokeN'
传递时,令牌为nil,方法为
如何在rails应用程序中通过标头传递持票人令牌?
答案 0 :(得分:16)
您可以使用以下方法获取Bearer令牌:
def bearer_token
pattern = /^Bearer /
header = request.headers['Authorization']
header.gsub(pattern, '') if header && header.match(pattern)
end
此外,设置标题时应该是:
Authorization: Bearer 'aUthEnTicAtIonTokeN'
答案 1 :(得分:3)
您的方法可以正常工作,您只需要在请求中使用正确的引号。
使用单引号'
不起作用,双引号为"
。
作为参考,rails使用Authorization:
方法处理以下任何格式的authenticate_with_http_token
标头中的标记:
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
我确信这份清单并非详尽无遗,但希望能够了解可行的方法。
答案 2 :(得分:0)
您也可以使用
request.headers['Authorization'].split(' ').last