Skip to main content

Subscribe to GoRails to get access to this episode and all other pro episodes, and new awesome content every month.

Subscribe Now
Only $19/month

Unlimited access. Cancel anytime.

22 JSON Web Tokens with Devise & Warden

Episode 167 · January 10, 2017

Add a Warden strategy to Devise to support JWT authentication with your Rails app

Authentication APIs


You can login the user with warden and not set cookies by adding store: false to what we used in the episode to login the user:

sign_in(user, store: false)


Subscribe or login to view the transcript for this episode.


victor hazbun (340 XP) on

Great tutorial.

Mark Oveson (4,370 XP) on

Love this series. I've implemented this devise/warden strategy in my own project. One correction: Because the `before_action` in the ApiController is changed from `:authenticate_token!` to `:authenticate_user!`, the `skip_before_action` in the AuthenticationController must also change to `authenticate_user!`, otherwise devise will reply with "You must sign in or sign up before continuing."

Keep the great material coming, Chris.

Mark Oveson (4,370 XP) on

One more thought: As you pointed out, many websites will want to accept both JWT requests and non-JWT requests via the same API. By adding `skip_before_action :verify_authenticity_token` without disabling non-JWT requests, don't we open a hole to CSRF attack from non-JWT requests?

Here's a possible solution; would love to have your thoughts.

In the API controller:

skip_before_action :verify_authenticity_token, if: :json_web_token_present?

def json_web_token_present?

In the User model:

class User < ActiveRecord::Base
attr_accessor :has_json_web_token

In the strategy:

def authenticate!
user = User.find(payload["sub"])
user.has_json_web_token = true
success! user

Chris Oliver (167,510 XP) on

Yeah that's correct, if you're doing both you'll want to make sure any forms submitted verify authenticity token and the JWT token is the only one that should skip that. 👍

Matthew Welke (1,220 XP) on

Just thought I'd share these two blog posts I found pretty useful when I looked for more detail on web tokens vs. cookies:

Antonio F. (550 XP) on


You can create an episode with the same typology using a project of this type:

rails new weather --api

thank you


Antonio F. (550 XP) on


I have a token problem if I use the 'jwt', '~> 2.0' gem of Invalid auth token when inserting a record.

Chris could you help me with this?

Thank you


Xiaohong, Deng (1,140 XP) on

for authentication_controller, skip_before_action :authenticate_token! should be changed to skip_before_action :authenticate_user! because ApiController has changed.

Login or create an account to join the conversation.