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

devise-jwt

> 后端框架
Open source

JWT token authentication with devise and rails

1.3K stars0 likes3 views
WebsiteGitHub

About

JWT token authentication with devise and rails

Devise::JWT

devise-jwt is a Devise extension which uses JWT tokens for user authentication. It follows secure by default principle.

This gem is just a replacement for cookies when these can't be used. As with cookies, a devise-jwt token will mandatorily have an expiration time. If you need that your users never sign out, you will be better off with a solution using refresh tokens, like some implementation of OAuth2.

You can read about which security concerns this library takes into account and about JWT generic secure usage in the following series of posts:

  • Stand Up for JWT Revocation
  • JWT Revocation Strategies
  • JWT Secure Usage
  • A secure JWT authentication implementation for Rack and Rails

devise-jwt is just a thin layer on top of warden-jwt_auth that configures it to be used out of the box with Devise and Rails.

Upgrade notes

v0.7.0

Since version v0.7.0 Blacklist revocation strategy has been renamed to Denylist while Whitelist has been renamed to Allowlist.

For Denylist, you only need to update the include line you're using in your revocation strategy model:

ruby
# include Devise::JWT::RevocationStrategies::Blacklist # before
include Devise::JWT::RevocationStrategies::Denylist

For Allowlist, you need to update the include line you're using in your user model:

ruby
# include Devise::JWT::RevocationStrategies::Whitelist # before
include Devise::JWT::RevocationStrategies::Allowlist

You also have to rename your WhitelistedJwt model to AllowlistedJwt, rename model/whitelisted_jwt.rb to model/allowlisted_jwt.rb and change the underlying database table to allowlisted_jwts (or configure the model to keep using the old name).

Installation

Add this line to your application's Gemfile:

ruby
gem 'devise-jwt'

And then execute:

$ bundle

Or install it yourself as:

$ gem install devise-jwt

Usage

First, you need to configure Devise to work in an API application. You can follow the instructions in this project wiki page Configuring Devise for APIs (you are more than welcome to improve them).

Secret key configuration

You have to configure the secret key that will be used to sign generated tokens. You can do it in the Devise initializer:

ruby
Devise.setup do |config|
  # ...
  config.jwt do |jwt|
    jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
  end
end

If you are using Encrypted Credentials (Rails 5.2+), you can store the secret key in config/credentials.yml.enc.

Open your credentials editor using bin/rails credentials:edit and add devise_jwt_secret_key.

Note you may need to set $EDITOR depending on your specific environment.

yaml

# Other secrets...

# Used as the base secret for Devise JWT
devise_jwt_secret_key: abc...xyz

Add the following to the Devise initializer.

ruby
Devise.setup do |config|
  # ...
  config.jwt do |jwt|
    jwt.secret = Rails.application.credentials.devise_jwt_secret_key!
  end
end

Important: You are encouraged to use a secret different than your application secret_key_base. It is quite possible that some other component of your system is already using it. If several components share the same secret key, chances that a vulnerability in one of them has a wider impact increase. In rails, generating new secrets is as easy as rails secret. Also, never share your secrets pushing it to a remote repository, you are better off using an environment variable like in the example.

Currently, HS256 algorithm is the one in use. You may configure a matching secret and algorithm name to use a different one (see ruby-jwt to see which are supported):

ruby
Devise.setup do |config|
  # ...
  config.jwt do |jwt|
    jwt.secret = OpenSSL::PKey::RSA.new(Rails.application.credentials.devise_jwt_secret_key!)
    jwt.algorithm = Rails.application.credentials.devise_jwt_algorithm!
  end
end

If the algorithm is asymmetric (e.g. RS256) which necessitates a different decoding secret, configure the decoding_secret setting as well:

ruby
Devise.setup do |config|
  # ...
  config.jwt do |jwt|
    jwt.secret = OpenSSL::PKey::RSA.new(Rails.application.credentials.devise_jwt_private_key!)
    jwt.decoding_secret = OpenSSL::PKey::RSA.new(Rails.application.credentials.devise_jwt_public_key!)
    jwt.algorithm = 'RS256' # or some other asymmetric algorithm
  end
end

Model configuration

You have to tell which user models you want to be able to authenticate with JWT tokens. For them, the authentication process will be like this:

  • A user authenticates through Devise create session request (for example, using the standard :database_authenticatable module).
  • If the authentication succeeds, a JWT token is dispatched to the client in the Authorization response header, with format Bearer #{token} (tokens are also dispatched on a successful sign up).
  • The client can use this token to authenticate following requests for the same user, providing it in the Authorization request header, also with format Bearer #{token}
  • When the client visits Devise destroy session request, the token is revoked.

See request_formats configuration option if you are using paths with a format segment (like .json) in order to use it properly.

As you see, unlike other JWT authentication libraries, it is expected that tokens will be revoked by the server. I wrote about why I think JWT revocation is needed and useful.

An example configuration:

ruby
class User  'bar' }
end

You can add a hook method on_jwt_dispatch on the user model. It is executed when a token dispatched for that user instance, and it takes token and payload as parameters.

ruby
def on_jwt_dispatch(token, payload)
  do_something(token, payload)
end

Note: if you are making cross-domain requests, make sure that you add Authorization header to the list of allowed request headers and exposed response headers. You can use something like rack-cors for that, for example:

ruby
config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://your.frontend.domain.com'
    resource '/api/*',
      headers: %w(Authorization),
      methods: :any,
      expose: %w(Authorization),
      max_age: 600
  end
end

Session storage caveat

If you are working with a Rails application that has session storage enabled and a default Devise setup, chances are the same origin requests will be authenticated from the session regardless of a token being present in the headers or not.

This is so because of the following default Devise workflow:

  • When a user signs in with :database_authenticatable strategy, the user is stored in the session unless one of the following conditions is met:
    • Session is disabled.
    • Devise config.skip_session_storage includes :params_auth.
    • Rails Request forgery protection handles an unverified request (but this is usually deactivated for API requests).
  • Warden (the engine below Devise), authenticates any request that the user has in the session without requiring a strategy (:jwt_authenticatable in our case).

So, if you want to avoid this caveat you have five options:

  • Disable the session. If you are developing an API, you probably don't need it. In order to disable it, change config/initializers/session_store.rb to:

    ruby
    Rails.application.config.session_store :disabled

    Notice that if you created the application with the --api flag you already have the session disabled.

  • If you still need the session for any other purpose, disable :database_authenticatable user storage. In config/initializers/devise.rb:

    ruby
    config.skip_session_storage = [:http_auth, :params_auth]
  • If you are using Devise for another model (e.g. AdminUser) and doesn't want to disable session storage for Devise entirely, you can disable it on a per-model basis:

    ruby
    class User  'bar')
    end

#### Denylist

In this strategy, a database table is used as a list of revoked JWT tokens. The `jti` claim, which uniquely identifies a token, is persisted. The `exp` claim is also stored to allow the clean-up of stale tokens.

In order to use it, you need to create the denylist table in a migration:

```ruby
def change
  create_table :jwt_denylist do |t|
    t.string :jti, null: false
    t.datetime :exp, null: false
  end
  add_index :jwt_denylist, :jti
end

For performance reasons, it is better if the jti column is an index.

Note: if you used the denylist strategy before version 0.4.0 you may not have the field exp. If not, run the following migration:

ruby
class AddExpirationTimeToJWTDenylist  'application/json', 'Content-Type' => 'application/json' }
    # This will add a valid token for `user` in the `Authorization` header
    auth_headers = Devise::JWT::TestHelpers.auth_headers(headers, user)

    get '/my/end_point', headers: auth_headers

    expect_something()
  end

Usually you will wrap this in your own test helper.

Configuration reference

This library can be configured calling jwt on Devise config object:

ruby
Devise.setup do |config|
  config.jwt do |jwt|
    # ...
  end
end

secret

Secret key is used to sign generated JWT tokens. You must set it.

rotation_secret

Allow rotating secrets. Set a new value to secret and copy the old secret to rotation_secret.

expiration_time

Number of seconds while a JWT is valid after its generation. After that, it won't be valid anymore, even if it hasn't been revoked.

Defaults to 3600 seconds (1 hour).

dispatch_requests

Besides the create session one, there are additional requests where JWT tokens should be dispatched.

It must be a bidimensional array, each item being an array of two elements: the request method and a regular expression that must match the request path.

For example:

ruby
jwt.dispatch_requests = [
                          ['POST', %r{^/dispatch_path_1$}],
                          ['GET', %r{^/dispatch_path_2$}],
                        ]

Important: You are encouraged to delimit your regular expression with ^ and $ to avoid unintentional matches.

revocation_requests

Besides the destroy session one, there are additional requests where JWT tokens should be revoked.

It must be a bidimensional array, each item being an array of two elements: the request method and a regular expression that must match the request path.

For example:

ruby
jwt.revocation_requests = [
                            ['DELETE', %r{^/revocation_path_1$}],
                            ['GET', %r{^/revocation_path_2$}],
                          ]

Important: You are encouraged to delimit your regular expression with ^ and $ to avoid unintentional matches.

request_formats

Request formats that must be processed (in order to dispatch or revoke tokens).

It must be a hash of Devise scopes as keys and an array of request formats as values. When a scope is not present or if it has a nil item, requests without format will be taken into account.

For example, with following config

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyauthenticationdevisejwtrails

No comments yet. Be the first to share.

> Details

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

> Related tools

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