简体   繁体   中英

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.

I want to authenticate users via token and I am therefore using the 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

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:

 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
  • you send the token header as access-token instead of auth_token

You can read about it in this github issue . It may not have been at the time of your problem, but it is currently published in the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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