我一直关注如何设置身份验证令牌的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很容易,但是如何设置默认值呢?
答案 0 :(得分:14)
标题名称不是HTTP_AUTHORIZATION
,你必须像这样设置它:
request['authorization'] = "Token token=#{token}"
能够使用authenticate_or_request_with_http_token
方法。
答案 1 :(得分:1)
查看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
答案 2 :(得分:0)
接受的答案不起作用。
在Rails 4中,它应该是request.authorization
而不是request['authorization']