Authentication with JWT in Rails API

Nurudeen Ibrahim
Mar 8, 2018 · 4 min read
gem 'jwt'
gem 'dotenv-rails'
JWT_SECRET='yoursecretkey'
class JsonWebToken
JWT_SECRET = ENV["JWT_SECRET"]
def self.encode(payload, exp = 24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, JWT_SECRET)
end
def self.decode(token)
body = JWT.decode(token, JWT_SECRET)[0]
HashWithIndifferentAccess.new body
rescue JWT::ExpiredSignature, JWT::VerificationError => e
raise ExceptionHandler::ExpiredSignature, e.message
rescue JWT::DecodeError, JWT::VerificationError => e
raise ExceptionHandler::DecodeError, e.message
end
end
module ExceptionHandler
extend ActiveSupport::Concern
class DecodeError < StandardError; end
class ExpiredSignature < StandardError; end
included do
rescue_from ExceptionHandler::DecodeError do |_error|
render json: {
message: "Access denied!. Invalid token supplied."
}, status: :unauthorized
end
rescue_from ExceptionHandler::ExpiredSignature do |_error|
render json: {
message: "Access denied!. Token has expired."
}, status: :unauthorized
end
end
end
class ApplicationController < ActionController::API
include ExceptionHandler
end
class Authentication
def initialize(user_object)
@username = user_object[:username]
@password = user_object[:password]
@user = User.find_by(username: @username)
end
def authenticate
@user && @user.authenticate(@password)
end
def generate_token
JsonWebToken.encode(user_id: @user.id)
end
end
class Authorization
def initialize(request)
@token = request.headers[:HTTP_TOKEN]
end
def current_user
JsonWebToken.decode(@token)[:user_id] if @token
end
end
class UsersController < ApplicationController  def login
auth_object = Authentication.new(login_params)
if auth_object.authenticate
render json: {
message: "Login successful!", token: auth_object.generate_token }, status: :ok
else
render json: {
message: "Incorrect username/password combination"}, status: :unauthorized
end
end
private def login_params
params.permit(:username, :password)
end
end
class GroupsController < ApplicationController  def post_message
authorization_object = Authorization.new(request)
current_user = authorization_object.current_user
if current_user == Group.find(params[:id]).created_by
# post message
else
# respond: You are not allowed to post to this group
end
end
end

Nurudeen Ibrahim

Written by

Software Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade