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.

27 How To Build APIs with Rails:

JSON Web Token Authentication From Scratch

Episode 166 · January 10, 2017

Add JWT Authentication to your Rails API from scratch

APIs Authentication


Transcripts

Subscribe or login to view the transcript for this episode.

Discussion


Fallback

So does this mean that the authentication is now also a token based API? Is this testable on postman?

I redid my whole authentication because I found that the Devise gem (the way it came out of the box) wasn't allowing me to make it into a token based API for me to use with my iOS app.

Fallback

This setup is for only accepting tokens to authenticate on the API. You can just pass over the Authorization header in Postman to test it out. You'll need a valid token, but just pass in "Authorization: bearer YOURTOKEN" as the header and that should do it.

Btw, the other episode I posted today shows how you can take this code and add it as a Devise strategy so you can use tokens to authenticate with Devise alongside cookies. Check that one out so you can see how to use Devise with it. :)


Fallback

Hey Chris,

Thanks for the great episode. There is a thing though that I don't understand. There can be many tokens for the same user (for instance the user logs in again --> everything is the same except secret signature OR a fake one that has the same payload). According to my understanding, to make sure everything goes fine you should check against the secret signature, but I don't see it in the video. When you create a token and send it back to the user, shouldn't you also save the token or at least the secret signature part of the token? Then when the client sends over the token you can check if the secret signature in the db is the same as in the request.

What you do in the video is only checking the payload part, and I don't really understand how that could work securely.

Fallback

The JWT gem we use verifies the signature every time you call decode on it, so every token is verified, as well as the expirations and other features it supports. It's fine to have multiple tokens per user (one for each device for example) but because things can change you want to use expirations so they can get a more recent version of the token. There's no need to store anything server-side in the db because this is designed to be stateless.

Does that make more sense?

Fallback

Thanks Chris! Yeah, I got it after this explanation.


Fallback

Very nice tutorial @excid3:disqus really made a lot of things clear.


Fallback

Such a great JWT series!! Thank you so much!
Really saving my life!)


Login or create an account to join the conversation.