Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

api_guard

> 后端框架
Open source

JWT authentication solution for Rails APIs

278 stars0 likes2 views
WebsiteGitHub

About

JWT authentication solution for Rails APIs

API Guard

JSON Web Token (JWT) based authentication solution with token refreshing & blacklisting for APIs built on Rails.

This is built using Ruby JWT gem. Currently API Guard supports only HS256 algorithm for cryptographic signing.

Table of Contents

  • Installation
  • Getting Started
    • Creating User model
    • Configuring Routes
    • Registration
    • Sign In (Getting JWT access token)
    • Authenticate API Request
    • Refresh access token
    • Change password
    • Sign out
    • Delete Account
  • Configuration
    • Default configuration
    • Access token validity
    • Access token signing secret
    • Invalidate tokens on password change
    • Token refreshing
    • Token blacklisting
  • Overriding defaults
    • Controllers
    • Routes
    • Adding custom data in JWT token payload
    • Override finding resource
    • Customizing / translating response messages using I18n
  • Testing
  • Wiki
    • Using API Guard with Devise
  • Contributing
  • License

Installation

Add this line to your application's Gemfile:

gem 'api_guard'

And then execute in your terminal:

$ bundle install

Or install it yourself as:

$ gem install api_guard

Getting Started

Below steps are provided assuming the model in User.

Creating User model

Create a model for User with below command.

$ rails generate model user name:string email:string:uniq password_digest:string

Then, run migration to create the users table.

$ rails db:migrate

Add has_secure_password in User model for password authentication.

Refer this Wiki for configuring API Guard authentication to work with Devise instead of using has_secure_password.

class User  3.1.7'

And then execute in your terminal:

$ bundle install

Configuring Routes

Add this line to the application routes (config/routes.rb) file:

api_guard_routes for: 'users'

This will generate default routes such as sign up, sign in, sign out, token refresh, password change for User.

Refer this Wiki for configuring API Guard routes to work with Devise.

Registration

This will create an user and responds with access token, refresh token and access token expiry in the response header.

Example request:

# URL
POST "/users/sign_up"

# Request body
{
    "email": "[email protected]",
    "password": "api_password",
    "password_confirmation": "api_password"
}

Example response body:

{
    "status": "success",
    "message": "Signed up successfully"
}

Example response headers:

Access-Token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NDY3MDgwMjAsImlhdCI6MTU0NjcwNjIyMH0.F_JM7fUcKEAq9ZxXMxNb3Os-WeY-tuRYQnKXr_bWo5E
Refresh-Token: Iy9s0S4Lf7Xh9MbFFBdxkw
Expire-At: 1546708020

The access token will only be valid till the expiry time. After the expiry you need to refresh the token and get new access token and refresh token.

You can customize the parameters of this API by overriding the controller code if needed.

Sign In (Getting JWT access token)

This will authenticate the user with email and password and respond with access token, refresh token and access token expiry in the response header.

To make this work, the resource model (User) should have an authenticate method as available in has_secure_password. You can use has_secure_password or your own logic to authenticate the user in authenticate method.

Example request:

# URL
POST "/users/sign_in"

# Request body
{
    "email": "[email protected]",
    "password": "api_password"
}

Example response body:

{
    "status": "success",
    "message": "Signed in successfully"
}

Example response headers:

The response headers for this request will be same as registration API.

You can customize the parameters of this API by overriding the controller code if needed.

Authenticate API Request

To authenticate the API request just add this before_action in the controller:

before_action :authenticate_and_set_user

Note: It is possible to authenticate with more than one resource, e.g. authenticate_and_set_user_or_admin will permit tokens issued for users or admins.

Send the access token got in sign in API in the Authorization header in the API request as below. Also, make sure you add "Bearer" before the access token in the header value.

Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NDY3MDgwMjAsImlhdCI6MTU0NjcwNjIyMH0.F_JM7fUcKEAq9ZxXMxNb3Os-WeY-tuRYQnKXr_bWo5E

Then, you can get the current authenticated user using below method:

current_user

and also, using below instance variable:

@current_user

Note: Replace _user with your model name if your model is not User.

Refresh access token

This will work only if token refreshing configured for the resource. Please see token refreshing for details about configuring token refreshing.

Once the access token expires it won't work and the authenticate_and_set_user method used in before_action in controller will respond with 401 (Unauthenticated).

To refresh the expired access token and get new access and refresh token you can use this request with both access token and request token (which you got in sign in API) in the request header.

Example request:

# URL
POST "/users/tokens"

# Request header
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NDY3MDgwMjAsImlhdCI6MTU0NjcwNjIyMH0.F_JM7fUcKEAq9ZxXMxNb3Os-WeY-tuRYQnKXr_bWo5E
Refresh-Token: Iy9s0S4Lf7Xh9MbFFBdxkw

Example response body:

{
    "status": "success",
    "message": "Token refreshed successfully"
}

Example response headers:

The response headers for this request will be same as registration API.

Change password

To change password of an user you can use this request with the access token in the header and new password in the body.

By default, changing password will invalidate all old access tokens and refresh tokens generated for this user and responds with new access token and refresh token.

Example request:

# URL
PATCH "/users/passwords"

# Request header
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NDY3MDgwMjAsImlhdCI6MTU0NjcwNjIyMH0.F_JM7fUcKEAq9ZxXMxNb3Os-WeY-tuRYQnKXr_bWo5E

# Request body
{
    "password": "api_password_new",
    "password_confirmation": "api_password_new"
}

Example response body:

{
    "status": "success",
    "message": "Password changed successfully"
}

Example response headers:

The response headers for this request will be same as registration API.

Sign out

You can use this request to sign out an user. This will blacklist the current access token from future use if token blacklisting configured.

Example request:

# URL
DELETE "/users/sign_out"

# Request header
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NDY3MDgwMjAsImlhdCI6MTU0NjcwNjIyMH0.F_JM7fUcKEAq9ZxXMxNb3Os-WeY-tuRYQnKXr_bWo5E

Example response:

{
    "status": "success",
    "message": "Signed out successfully"
}

Delete account

You can use this request to delete an user. This will delete the user and its associated refresh tokens.

Example request:

# URL
DELETE "/users/delete"

# Request header
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NDY3MDgwMjAsImlhdCI6MTU0NjcwNjIyMH0.F_JM7fUcKEAq9ZxXMxNb3Os-WeY-tuRYQnKXr_bWo5E

Example response:

{
    "status": "success",
    "message": "Account deleted successfully"
}

Configuration

To configure the API Guard you need to first create an initializer using

$ rails generate api_guard:initializer

This will generate an initializer named api_guard.rb in your app config/initializers directory with default configurations.

Default configuration

config/initializers/api_guard.rb

…

Access token validity

By default, the validity of the JWT access token is 1 day from the creation. Override this by configuring token_validity

config.token_validity = 1.hour # Set one hour validity for access tokens

On accessing the authenticated API with expired access token, API Guard will respond 401 (Unauthenticated) with message "Access token expired".

Refresh token validity

By default, the validity of the refresh token is 2 weeks from the creation. Override this by configuring refresh_token_validity

config.refresh_token_validity = 6.hours # Set six hours validity for refresh tokens

On accessing the refresh token API with expired refresh token, API Guard will respond 401 (Unauthenticated) with message "Invalid refresh token".

Access token signing secret

By default, the secret_key_base from the Rails secrets will be used for signing (encoding & decoding) the JWT access token. Override this by configuring token_signing_secret

config.token_signing_secret = 'my_signing_secret'

Note: Avoid committing this token signing secret in your version control (GIT) and always keep this secure. As, exposing this allow anyone to generate JWT access token and give full access to APIs. Better way is storing this value in environment variable or in encrypted secrets (Rails 5.2+)

Invalidate tokens on password change

By default, API Guard will not invalidate old JWT access tokens on changing password. If you need, you can enable it by configuring invalidate_old_tokens_on_password_change to true.

Note: To make this work, a column named token_issued_at with datatype datetime is needed in the resource table.

config.invalidate_old_tokens_on_password_change = true

If your app allows multiple logins then, you must set this value to true so that, this prevent access for all logins (access tokens) on changing the password.

Token refreshing

To include token refreshing in your application you need to create a table to store the refresh tokens.

Use below command to create a model RefeshToken with columns to store the token and the user reference

$ rails generate model refresh_token token:string:uniq user:references expire_at:datetime

Then, run migration to create the refresh_tokens table

$ rails db:migrate

Note: Replace user in the above command with your model name if your model is not User.

After creating model and table for refresh token configure the associatio

Issues· 12 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyapiapi-authapi-authenticationapi-guard

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架