How to create an RESTful API Service on Rails using JWT as authentication method
Using devise as base athentication method and JWT for Api
Posted on March 06, 2024
Apis are the default standard for communication between services and apps. Adding a layer for security and authenticated access is a basic requirement for any Restful Api.
JWT is a popular and stable method for authentication, for Rails we will use thedevise-jwtgem, so we must add and install it on our project. Once installed and setup we proceed to create and login endpoint for create new session.
Add a new namespace for API on our routes file.
namespace :api do
devise_for :users, defaults: { format: :json }, controllers: {
sessions: 'api/users/sessions',
}
get 'orders', to: 'orders#index', as: 'orders'
end
Add a new session controller under the api namespace.
class Api::Users::SessionsController < Devise::SessionsController
skip_before_action :verify_authenticity_token
def create
user = User.find_by_email(sign_in_params[:email])
if user && user.valid_password?(sign_in_params[:password])
token = user.generate_jwt
render json: token.to_json
else
render json: { errors: { 'email or password' => ['is invalid'] } }, status: :unprocessable_entity
end
end
protected
def sign_in_params
params.require(:session).permit(:email, :password, :password_confirmation)
end
end
As the gem recommend on the documentation we use the self revocation strategy and define the generate_jwt method as follows (can set the constant DAYS_EXPIRE_POLICY as the number of days of existence of the token):
def generate_jwt
JWT.encode({id: id, exp: DAYS_EXPIRE_POLICY.days.from_now.to_i}, Rails.application.secrets.secret_key_base)
end
Test on Postman
For this example, we have the following basic schema:
So we add and endpoint for retrieving the list of orders created by a user:
Route on the api namespace:
get 'orders', to: 'orders#index', as: 'orders'
Controller:
class Api::OrdersController < Api::BaseApiController
def index
render json: {
success: true,
orders: current_user.orders.map(&:to_json)
}
end
end
How to validate token
For validate the JWT Token create a BaseApi controller for handled all JSON API request and define the following method:
def process_token
if request.headers['Authorization'].present?
begin
jwt_payload = JWT.decode(request.headers['Authorization'].split(' ')[1], Rails.application.secrets.secret_key_base).first
@current_user_id = jwt_payload['id']
rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError
head :unauthorized
end
end
end
As you can see we must use the Rails secret for decrypt and validate the token with the JWT.decode method