JWT::Auth

JWT-based authentication middleware for Rails API without Devise
Installation
Add this line to your application's Gemfile:
gem 'jwt-auth'
And then execute:
$ bundle
Or install it yourself as:
$ gem install jwt-auth
Usage
Create an initializer:
JWT::Auth.configure do |config|
##
# Token lifetime
#
config.token_lifetime = 24.hours
##
# JWT secret
#
config.secret = Rails.application.secrets.secret_key_base
end
Do not try to set the model configuration property in the initializer, as this property is already set by including the Authenticatable concern in your model.
Include model methods in your user model:
class User < ApplicationRecord
include JWT::Auth::Authenticatable
end
Optionally, define the find_by_token method on your model to allow additional checks (for example account activation):
def self.find_by_token(params)
find_by params.merge :activated => true
end
Add a token_version field to your user model:
class AddTokenVersionToUser < ActiveRecord::Migration[5.0]
def change
add_column :users, :token_version, :integer, :null => false, :default => 1
end
end
Include controller methods in your ApplicationController and handle unauthorized errors:
class ApplicationController < ActionController::API
include JWT::Auth::Authentication
rescue_from JWT::Auth::UnauthorizedError, :with => :handle_unauthorized
protected
def
head :unauthorized
end
end
Set callbacks on routes:
class MyController < ApplicationController
# Authenticates user from request header
# The callback raises an UnauthorizedError on missing or invalid token
before_action :authenticate_user, :except => %i[create]
# Validate token if there is a token present
# The callback raises an UnauthorizedError only if there is a token present, and it is invalid
# This prevents users from using an expired token on an unauthenticated route and getting a HTTP 2xx
before_action :validate_token
# Renew token and set response header
after_action :renew_token
end
Contributing
- Fork it ( https://github.com/floriandejonckheere/jwt-auth/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request