DEV Community

Discussion on: Ruby on Rails API Simple authentication with JWT

Collapse
 
protocod profile image
Maximilien Di Dio

Hello !
Thank you for your article !

But I'm wondering about something in your authentication function from ApplicationController.

user_data = decode_data[0]["user_id"] unless !decode_data
# find a user in the database to be sure token is for a real user
user = User.find(user_data&.id)
Enter fullscreen mode Exit fullscreen mode

I may be wrong but you're not supposed to call the database here. JWT was created to avoid to call the database when the user have to be authorized.
(this function should maybe named authorization ? Because the client provide a token, not credentials)
A REST API can be called by a Human or an Application. It's maybe not a good idea to call the User model anyway.

Thank you this article again ! I'll follow you on dev.to :D

Collapse
 
fc_name profile image
fc_name

Hi. It is different to go to the database to fetch the existing of a token (that usually is sent from front end to back end and then matched to db), than looking up an index integer PK, aka the user id. Because it's an integer lookup as well as this happening on an indexed column is much fast than doing string comparison against tokens.

So, it's not the same as session authentication with a DB-stored token. it's much faster, and it's anyway the only way to fetch the user on the backend once receiving the JWT. After all, there should no be private information on JWT (e.g. email) since it is just encoded and not encrypted and it can be decoded by anyone.

Collapse
 
codesalley profile image
Code Salley

Thank you so much, yes it a complex app it’s not a good advice to do this. But in this case We need to know if the user really in the database