【问题标题】:set authentication token in http header在 http 标头中设置身份验证令牌
【发布时间】:2023-03-09 21:26:01
【问题描述】:

我一直在关注关于如何设置身份验证令牌的 railscast http://railscasts.com/episodes/352-securing-an-api?view=asciicast

我已经很好地设置了我的应用程序,它使用 authenticate_or_request_with_http_token 方法来获取令牌。

我的问题是我有一个需要在标头中设置令牌的下一个应用程序。 比如:

uri = URI.parse(full_url)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request['HTTP_AUTHORIZATION'] = 'this_is_a_test_key'
response = http.request(request)

上面的代码被拒绝访问。我知道设置 X-CUSTOM-TOKEN 之类的自定义设置很容易,但是如何设置默认设置?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    标题名称不是HTTP_AUTHORIZATION,您必须像这样设置它:

    request['authorization'] = "Token token=#{token}"
    

    为了能够使用authenticate_or_request_with_http_token方法。

    【讨论】:

      【解决方案2】:

      查看ActionController::HttpAuthentication 模块,例如

      user = 'whatever'
      pass = 'you-like'
      auth = ActionController::HttpAuthentication::Basic.encode_credentials(user, pass)
      request.headers['Authorization'] = auth
      

      同理,例如

      token = 'whatever-it-is'
      auth = ActionController::HttpAuthentication::Token.encode_credentials(token)
      request.headers['Authorization'] = auth
      

      【讨论】:

        【解决方案3】:

        接受的答案无效。

        在 Rails 4 中,它应该是 request.authorization 而不是 request['authorization']

        【讨论】:

          猜你喜欢
          • 2017-08-12
          • 1970-01-01
          • 2012-12-12
          • 1970-01-01
          • 1970-01-01
          • 2015-05-08
          • 2016-10-21
          • 2013-09-28
          • 1970-01-01
          相关资源
          最近更新 更多