-
Notifications
You must be signed in to change notification settings - Fork 27
Using API Guard with Devise
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.
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,
- Defining path prefix
- Keeping routes in separate subdomain
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.
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.
As we already have Devise installed we can use the authentication strategy provided by Devise instead of using has_secure_password
. 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 don't 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.