Search code examples
deviserubygemsruby-on-rails-4.2

Does "devise_token_auth" gem support web-based authentication?


This gem ("devise_token_auth") is used for token authentication for applications using JSON APIs for front-end development. Can we use this gem for server side rendering? If yes, then how to add the token from a previous response to the current request?


Solution

  • I don't know if this is still a pressing matter for you, but I'd like to throw in some advice.

    For your API you can throw in devise_token_auth and it will do what everything you need for authentication there.

    And if you need authentication with server-side rendering of pages (such as login forms, reset password forms, etc.) just throw in regular devise too. It will work with your exact same User model and table, and there will be little friction to get things up and running with the same resources you use with devise_token_auth.

    Gemfile

    #autentication and authorization
    gem 'devise', '~> 3.5', '>= 3.5.6'
    gem 'devise_token_auth', '0.1.37'
    

    Then run

    bundle
    

    Run the installer for devise:

    rails generate devise:install
    

    Then generate your user model:

    rails generate devise User
    

    Install devise_token_auth now:

    rails g devise_token_auth:install User "auth"
    

    And make sure your database is migrated:

    rake db:migrate
    

    I think devise_token_auth may overwrite your user model, I'm not certain, but if it does, keep the migrations for devise_token_auth only and ignore the migrations for Devise.

    Then make sure your routes.rb matches this:

    Rails.application.routes.draw do
    
      devise_for :users
      root "home#index"
    
      namespace :api, defaults: { format: :json } do
        namespace :v1 do #I namespace my routes
          mount_devise_token_auth_for "User", at: "auth"
        end
      end
    
    end
    

    devise_for must come before mount_devise_token_auth.

    Then just refer to the official devise and devise token auth documentation to get both solutions working for you.

    Hope this helps anyone who reaches this point and has a need to authenticate users on mobile app and on browser web app.