Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Implementing Token Based Authentication in Rails

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 558
    Comment on it

    In modern world, most of the web applications are api based. So using api's we also need to validate the authenticity of the user. When it is a proper web application the authentication of the user is maintained using cookies and sessions. But in case of api's it is not possible using the conventional way because the request is coming from other devices. So for authenticating user in api based application one way of authentication is Token Based Authentication.

    Token Based Authentication can be simply understood as, whenever a user is created an auth token is saved along with the user. So whenever the user logs in with proper user name and password, that auth token is returned to the user. So whenever the user hits the next request, he sends the token received. Thus the application recognizes the user is the same logged in user.

    There are different way to follow this approach. In rails as we all know the best way for authenticating user is devise, but it doesn't provide feature for token based authentication, so we need to integrate some other plugin that can support both the devise and our token based authentication approach. One of the gem is simple_token_authentication. It is dependent on devise.

    Lets see how it works:

    1) Create a rails application

    > rails new api_based_project

    2) Add devise gem to your Gemfile and run bundle

    gem 'devise'

    3) Install devise using devise generator

    > rails generate devise:install
    

    4) Config the mailer in your config/environments/development.rb

    config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

    5) Now generate devise for your User model. It will create User model if it doesn't exist already

    > rails generate devise User
    

    6) Now run migrations

    > rake db:migrate
    

    7) So Now when the devise is installed lets switch towards the token based authentications, so lets add the gem in your Gemfile

    gem 'simple_token_authentication', '~> 1.0'

    8) Now make user model token authenticable by adding the following line into it.

    acts_as_token_authenticatable
    

    9) Now add the authentication_token field in your user model

    rails g migration add_authentication_token_to_users "authentication_token:string{30}:uniq"

    10) Run the migration

    rake db:migrate

    11) Now inside your controller where you want to handle the authentication add the following line, in our case we will add it inside the application controller.

    class ApplicationController < ActionController::Base
        # Prevent CSRF attacks by raising an exception.
        # For APIs, you may want to use :null_session instead.
        # protect_from_forgery with: :exception
      acts_as_token_authentication_handler_for User
    end

    12) As we are creating this application to only accept the api's we will comment the following line from the application controller

    # protect_from_forgery with: :exception

    13) Because of this gem whenever a user will be created by default an authentication_token will be saved automatically with the user. So now lets create a user using console.

    > user = User.new(email:"abc@gmail.com", password: "12345678", password_confirmation: "12345678")
    
    => #<User id: nil, email: "abc@gmail.com", created_at: nil, updated_at: nil, authentication_token: nil> 
    
    
    > user.save
    
    	
    =>   (0.2ms)  BEGIN
      User Exists (1.2ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "abc@gmail.com"], ["LIMIT", 1]]
       (0.5ms)  SELECT COUNT(*) FROM "users" WHERE "users"."authentication_token" = $1  [["authentication_token", "zYr4TUNBBDZ6nDm69t_z"]]
      SQL (0.9ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at", "authentication_token") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["email", "abc@gmail.com"], ["encrypted_password", "$2a$11$VOgxx95rU3NpFkK.6cELN.9dKcM43iCgi3YsAXTfBTEELyB80HZ2q"], ["created_at", 2016-07-25 05:24:58 UTC], ["updated_at", 2016-07-25 05:24:58 UTC], ["authentication_token", "zYr4TUNBBDZ6nDm69t_z"]]
       (14.4ms)  COMMIT
     => true 
    
    
    > user.authentication_token
    
    => "zYr4TUNBBDZ6nDm69t_z" 

    Thus you can see the authentication_token automatically got saved with the user as soon as it got created. Now whenever user gives a signin request with correct user name and password this authentication token will be reverted with the authentication success response and in every next request the user must pass this token for authorizing.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: