Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"=>"[email protected]", "client"=>"NAzWNJalYBJLRni9dCGxXA"}
 Completed 401 Unauthorized in 0ms (Views: 0.1ms | ActiveRecord: 0.0ms)

What am I doing wrong? How can I solve this?

like image 807
fmlopes Avatar asked Jun 22 '16 14:06

fmlopes


1 Answers

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.

like image 160
Todd Avatar answered Oct 24 '22 06:10

Todd