Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Token authentication with Rails and Devise

I'm following this excellent article to setup the authentification part of my rails (3.2) API:
http://blog.joshsoftware.com/2011/12/23/designing-rails-api-using-rabl-and-devise/

I have done the following step:

-Added devise to Gemfile

-Enabled devise for the user model and ran the migrations required

-My user model is

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
  devise :token_authenticatable

  attr_accessible :email, :authentication_token, :password, :password_confirmation, :remember_me
end

as well as the token_authenticable in Database (via a migration).

-Subclassed the RegistrationController with:

class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => " {controller_path}#new")
    sign_in(resource_name, resource)
    current_user.reset_authentication_token!
    respond_with resource, :location => after_sign_in_path_for(resource)
  end

  def update
    super
  end
end

-In routes.rb, I have:

devise_for :users, :controllers => {:registrations => "registrations"}

USER CREATION

I'd like the following request to create a user and to send back the authentification_token:

curl -H "Accept: application/json" -H "Content-type: application/json"  -X POST -d '{"user":{"email":"[email protected]", "password":"pass"}}' 'http://localhost:3000/users.json

My understanding is that the logic should go in the "create" method of the registration controller (that should create the user and log him in at the same time). I think I should be wrong as the message I got in return is:

{"error":"You need to sign in or sign up before continuing."}

What is the missing piece to have the new user created and logged ? Isn't POST to users.json mapped to RegistrationController#create ?

USER LOGIN

Also, I'd like the following request to log a user in (sending him back his authentification_token once the login / password have been checked)

curl -H "Accept: application/json" -H "Content-type: application/json"  -X GET -d '{"user":{"email":"[email protected]","password":"pass"}}' 'http://localhost:3000/users.json

I guess the logic should go in the "update" method of RegistrationController but not 100% sure about that. Once the login is done I will then add the token authentification to protect the creation / view of some other models.

UPDATE

When I issue:

curl -H "Accept: application/json" -H "Content-type: application/json"  -X POST -d '{"user":{"email":"[email protected]", "password": "mypass", "phone":"1234567890"}}' 'http://localhost:3000/users.json'

I got the following message:

Started POST "/users.json" for 127.0.0.1 at 2012-03-11 20:50:05 +0100
Processing by RegistrationsController#create as JSON
Parameters: {"user"=>{"email"=>"[email protected]", , "password"=>"[FILTERED]", "phone"=>"1234567890"}, "registration"=>{"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "phone"=>"1234567890"}, "action"=>"create", "controller"=>"registrations", "format"=>"json"}}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 1ms

Any ideas why the user is not created and signed in and why no authentication_token is returned ?

like image 345
Luc Avatar asked Mar 09 '12 21:03

Luc


People also ask

How does authentication token work in Rails?

The authenticate action will take the JSON parameters for email and password through the params hash and pass them to the AuthenticateUser command. If the command succeeds, it will send the JWT token back to the user.

How token based authentication works in REST API?

Users of the REST API can authenticate by providing a user ID and password to the REST API login resource with the HTTP POST method. An LTPA token is generated that enables the user to authenticate future requests. This LTPA token has the prefix LtpaToken2 .

What is JWT Token in rails?

JSON Web Tokens, commonly known as JWT is an open standard for representing and verifying claims securely between a client and a server. It is one of the most popular authentication and authorization techniques employed in modern applications.


1 Answers

It's my fault, I'll update the blog post. You need to add the following code to create the user in you registration controller

if params[:api_key].blank? or params[:api_key] != API_KEY
  render :json => {'errors'=>{'api_key' => 'Invalid'}}.to_json, :status => 401
  return
end
build_resource
if resource.save
   sign_in(resource)
   resource.reset_authentication_token!
   #rabl template with authentication token
   render :template => '/devise/registrations/signed_up' 
else
   render :template => '/devise/registrations/new' #rabl template with errors 
end

Let me know if you face any problem?

like image 172
Sethupathi Avatar answered Oct 17 '22 18:10

Sethupathi