在http标头中设置身份validation令牌

我一直关注如何设置身份validation令牌的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很容易,但是如何设置默认值呢?

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

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

能够使用authenticate_or_request_with_http_token方法。

查看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 

接受的答案不起作用。

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