如何通过rails中的标头传递持有者令牌?

sat*_*t's 10 authentication ruby-on-rails bearer-token

在我的rails应用程序中,我能够Authorization: Token token='aUthEnTicAtIonTokeN'通过请求标头传递令牌

authenticate_with_http_token do |token, options|
 @auth_token = token
end
Run Code Online (Sandbox Code Playgroud)

但是当我传递令牌作为Authorization: Bearer token='aUthEnTicAtIonTokeN'获取令牌为nil的方法时.

如何在rails应用程序中通过标头传递不记名令牌?

Ale*_*x.U 19

您可以通过以下方法获取Bearer令牌:

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

此外,设置标题时应该是:

Authorization: Bearer 'aUthEnTicAtIonTokeN'
Run Code Online (Sandbox Code Playgroud)


pro*_*oob 5

您的方法将按原样正确运行,您只需要在请求中使用正确的引号即可。

使用单引号'无效,而使用双引号则无效"

作为参考,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
Run Code Online (Sandbox Code Playgroud)

我确定此列表并不详尽,但希望能给出可能的想法。


Sco*_*son 5

你也可以使用

request.headers['Authorization'].split(' ').last
Run Code Online (Sandbox Code Playgroud)