[Ruby On Rails] Authentication for Restful Services – API Key (Token)

One of the popular ways to authenticate users in Restful services is to use a token. You can provide a temporary or permanent token (key) to a user and the token is provided in each request.

1. Create a Model

Create a model to save a key or token.

> rails g model api_key access_token:string
> rake db:migrate

And then modify the “ApiKey” model class.

class ApiKey < ActiveRecord::Base

  before_create :generate_access_token

  validates :access_token, uniqueness: true

    def generate_access_token
        self.access_token = SecureRandom.hex
      end while self.class.exists?(access_token: access_token)

It creates a unique random key.


2. Signing In/Out

You need another controller to generate or erase a key.

> rails g controller Account

class AccountController < ApplicationController
  def signin
    token = ApiKey.create!
    msg = { token: token.access_token }
    respond_to do |format|
      format.html { render text: token.access_token }
      format.json { render json: msg }

  def signout
    authenticate_or_request_with_http_token do |token, options|
      token = ApiKey.find_by(access_token: token)
      if token != nil
    msg = { status: "OK" }
    respond_to do |format|
      format.html { render text: msg[:status] }
      format.json { render json: msg }

And add the routes for the actions.

match '/signin', to: 'account#signin',     via: 'get'
match '/signout', to: 'account#signout',   via: 'get'


3. Securing Actions

In the controller, you can verify the token.

before_action :restrict_access, except: [:index]


  def restrict_access
    authenticate_or_request_with_http_token do |token, options|
      ApiKey.exists?(access_token: token)

You can add more logic here. One idea is to invalidate the token that is older than your validation period (such as a day).


4. How to Send a Token

At first you need to request a token through the “signin” route or get it from the administrator.

And then include the token in your request header.

Authorization: Token  token="2d5ee5999222c706e7a5a9f91f37def5"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s