Skip to content

Using API Guard with Devise

Gokul Murali edited this page Feb 2, 2020 · 3 revisions

We need to do below customizations for using API Guard with Devise by which we can authenticate the APIs with API Guard and browser sessions with Devise.

Note: The below instructions are written assuming your app already have a model for the resource (E.g. User) and configured with devise authentication.

Routes:

As the routes generated by Devise and API Guard are mostly same we need to separate the API Guard default routes (sign up, sign in, etc.) from Devise generated routes.

This can be done by several ways but below two ways are easy to setup,

  1. Defining path prefix
  2. Keeping routes in separate subdomain

1. Defining path prefix

Add prefix to the API Guard routes.

scope path: 'api' do
  api_guard_routes for: 'users'
end

This will add prefix api/ for all the API Guard routes.

2. Keeping routes in separate subdomain

Add API Guard routes under a subdomain.

constraints subdomain: 'api' do
  api_guard_routes for: 'users'
end

Important Note: The above code should be added above devise routes in the routes.rb file.

This will make the API Guard routes available only in api subdomain.

Authentication

As we already have Devise installed we can use the authentication strategy provided by Devise for API Guard too. We just need to define an instance method in the resource model (E.g. User) as below for API Guard authentication to work.

class User < ApplicationRecord
  def authenticate(password)
    valid_password?(password)
  end
end

For this, we no need to add a column named password_digest in the resource model as we should already have column for storing the encrypted password using Devise.

Clone this wiki locally
You can’t perform that action at this time.