简体   繁体   English

如何在devise_token_auth gem中成功使用validate_token?

[英]How to successfully use validate_token in the devise_token_auth gem?

I am fairly new to Ruby and Rails itself and I'm trying to build a simple Rails API. 我对Ruby和Rails本身很新,我正在尝试构建一个简单的Rails API。

I want to authenticate users via token and I am therefore using the devise_token_auth gem. 我想通过令牌验证用户,因此我使用devise_token_auth gem。

I can successfully make a POST request at /auth/sign_in and I am now trying to make a GET request at /auth/validate_token 我可以在/ auth / sign_in成功发出POST请求,我现在正在尝试在/ auth / validate_token发出GET请求

What I have, as a "test": 我所拥有的,作为“测试”:

    uri = URI.parse("http://localhost:3000/auth/sign_in")
    response = Net::HTTP.post_form(uri, {"email" => params[:session][:email], "password" => params[:session][:password]})

    uri2 = URI.parse("http://localhost:3000/auth/validate_token")
    params = { :auth_token => response['access-token'], :uid => response['uid'], :client => response['client'] }
    uri2.query = URI.encode_www_form(params)
    response2 = Net::HTTP.get_response(uri2)

I am therefore using the access-token and uid retrieved from the response header but I keep getting a 401 response code from /auth/validate_token: 因此,我使用从响应头中检索的访问令牌和uid,但我不断从/ auth / validate_token获得401响应代码:

 Started GET "/auth/validate_token?auth_token=EEV40VDHfOaWtBzv3bn_DQ&uid=username%40example.com&client=NAzWNJalYBJLRni9dCGxXA" for ::1 at 2016-06-22 15:22:35 +0100
 Processing by DeviseTokenAuth::TokenValidationsController#validate_token as */*
   Parameters: {"auth_token"=>"EEV40VDHfOaWtBzv3bn_DQ", "uid"=>"username@example.com", "client"=>"NAzWNJalYBJLRni9dCGxXA"}
 Completed 401 Unauthorized in 0ms (Views: 0.1ms | ActiveRecord: 0.0ms)

What am I doing wrong? 我究竟做错了什么? How can I solve this? 我怎么解决这个问题?

I believe the problem is twofold: 我认为这个问题是双重的:

  • you send the authentication credentials as headers to the /validate_token endpoint 您将身份验证凭据作为标头发送到/ validate_token端点
  • you send the token header as access-token instead of auth_token 您将令牌标头作为access-token而不是auth_token

You can read about it in this github issue . 你可以在这个github问题中阅读它。 It may not have been at the time of your problem, but it is currently published in the README . 它可能不是您出现问题的时候,但它目前已在README中发布。

Here are all the headers necessary for a valid authenticated request (at the time of this writing): 以下是有效身份验证请求所需的所有标头(在撰写本文时):

"access-token": "wwwww", "token-type": "Bearer", "client": "xxxxx", "expiry": "yyyyy", "uid": "zzzzz"

Note: these are not necessary for every endpoint, but usually access-token , client , and uid are. 注意:这些对于每个端点都不是必需的,但通常是access-tokenclientuid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM