【问题标题】:How to get bearer token passed through header in rails?如何让不记名令牌通过rails中的标头传递?
【发布时间】:2017-11-03 13:06:56
【问题描述】:

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

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

但是当我将令牌作为Authorization: Bearer token='aUthEnTicAtIonTokeN' 传递时,上述方法将令牌作为零。

如何在 Rails 应用程序中通过标头获取不记名令牌?

【问题讨论】:

    标签: ruby-on-rails authentication bearer-token


    【解决方案1】:

    您可以使用以下方法获取 Bearer 令牌:

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

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

    Authorization: Bearer 'aUthEnTicAtIonTokeN'
    

    【讨论】:

      【解决方案2】:

      您的方法将按原样正常工作,您只需要在请求中使用正确的引号。

      使用单引号 ' 不起作用,而双引号 " 则起作用。

      作为参考,rails 使用 authenticate_with_http_token 方法以下列任何格式处理来自 Authorization: 标头的标记:

      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
      

      我敢肯定,这份清单并不详尽,但希望能说明什么是可能的。

      【讨论】:

        【解决方案3】:

        你也可以使用

        request.headers['Authorization'].split(' ').last
        

        【讨论】:

          猜你喜欢
          • 2014-12-03
          • 2013-06-09
          • 1970-01-01
          • 1970-01-01
          • 2019-09-25
          • 2017-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多