JWT token authentication with devise and rails
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:
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.
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:
# include Devise::JWT::RevocationStrategies::Blacklist # before
include Devise::JWT::RevocationStrategies::DenylistFor Allowlist, you need to update the include line you're using in your user model:
# include Devise::JWT::RevocationStrategies::Whitelist # before
include Devise::JWT::RevocationStrategies::AllowlistYou 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).
Add this line to your application's Gemfile:
gem 'devise-jwt'And then execute:
$ bundleOr install it yourself as:
$ gem install devise-jwtFirst, 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).
You have to configure the secret key that will be used to sign generated tokens. You can do it in the Devise initializer:
Devise.setup do |config|
# ...
config.jwt do |jwt|
jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
end
endIf 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
$EDITORdepending on your specific environment.
# Other secrets...
# Used as the base secret for Devise JWT
devise_jwt_secret_key: abc...xyzAdd the following to the Devise initializer.
Devise.setup do |config|
# ...
config.jwt do |jwt|
jwt.secret = Rails.application.credentials.devise_jwt_secret_key!
end
endImportant: 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 asrails 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):
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
endIf the algorithm is asymmetric (e.g. RS256) which necessitates a different decoding secret, configure the decoding_secret setting as well:
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
endYou 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:
:database_authenticatable module).Authorization response header, with format Bearer #{token} (tokens are also dispatched on a successful sign up).Authorization request header, also with format Bearer #{token}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:
class User 'bar' }
endYou 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.
def on_jwt_dispatch(token, payload)
do_something(token, payload)
endNote: 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:
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
endIf 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:
:database_authenticatable strategy, the user is
stored in the session unless one of the following conditions is met:config.skip_session_storage includes :params_auth.: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:
Rails.application.config.session_store :disabledNotice 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:
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:
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
endFor 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:
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()
endUsually you will wrap this in your own test helper.
This library can be configured calling jwt on Devise config object:
Devise.setup do |config|
config.jwt do |jwt|
# ...
end
endSecret key is used to sign generated JWT tokens. You must set it.
Allow rotating secrets. Set a new value to secret and copy the old secret to rotation_secret.
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).
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:
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.
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:
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 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
No open issues yet, or sync has not completed.