Skip to content

Token Authentication

Logan Serman edited this page May 29, 2015 · 8 revisions

This gem provides a custom Devise authentication strategy that brings back token authentication through the HTTP Authorization header.

Authenticated routes should be provided both the user's authentication token AND id (this is to prevent timing attacks on the backend). For example:

Authorization: Token token=7dfb4853ba75193a99199f13c4e5b020aaba63cf, id=123

Rails Setup

Add this to config/initializers/devise.rb:

config.warden do |manager|
  manager.strategies.add(:token_authenticatable, Devise::Strategies::TokenAuthenticatable)
  manager.default_strategies(scope: :user).unshift :token_authenticatable
end

You may have to change :user according to your model name.

Make your user model token authenticatable:

devise :database_authenticatable, :registerable, ..., :token_authenticatable

You will also need some fields added to your User model if you don't have them already:

def change
  add_column :users, :authentication_token, :string
  add_column :users, :token_expires_at, :datetime
end

By default, tokens will expire every 14 days. You can change this by overriding expire_token_in on your User model.

def expire_token_in
  20.years
end
Clone this wiki locally