DEV Community

Understanding JWT Authentication: A Comprehensive Guide with Examples

Vishal Yadav on June 21, 2024

In the world of web development, security is paramount. One of the most popular methods for securing web applications is JSON Web Token (JWT) authe...
Collapse
 
kevinduffey profile image
kevinduffey

Good primer but a bit was left out that would probably be helpful for someone thinking about JWT vs say, OAUTH2 or an API token. In particular I'd add that first, you should NEVER store JWT tokens in local storage. The server should always use httpOnly flag, and it should only be done over SSL/TLS. "But then the client cant read the token data and get info like user id, name, etc from the token". Yup. That info should be returned as part of the body response on login when the token is also returned. Any details like user name, email, etc that need to be used in the app, should only come back on login as the response body. This ensures that nobody on the client or in between client and server (say.. an extension for example ) can access the token and use it for nefarious purposes.

The second thing I'd add is that you almost always want a refresh token AND an access token generated. The refresh token is long lived.. maybe 30 days, or just 1 day, if your domain requires daily logins. The access token is short lived. I'd argue 30 minutes max, but I typically have mine at 5 minutes. The access token contains the details like RBAC, etc.. that the server side uses to determine if the request being made is allowed. It is also used to enable invalidation of a user. For example, a user is an employee.. who got fired but had logged in 1 minute prior. Well now they are angry and they can wreak havoc for as long as that access token allows them to (assuming their "role" in the token allows them to do nefarious things). But HR invalidates their user account. When the access token expires in a few minutes.. the refresh token is used to look up their user account (e.g. similar to a login) but perhaps its in a Redis table or some other manner in which a user account is used. The point is, at that point the account is discovered to be disabled, so the refresh token is now invalidated and a 401 is returned. The client side will then redirect to a login page again, and when they try to log in.. no longer can do so. This method avoids having to have some sort of server side Redis blacklist DB to keep track of all users, etc.

Collapse
 
matin_mollapur profile image
Matin Mollapur

this is an excellent breakdown of jwt authentication! you covered the essential concepts and provided clear examples, making it easy to understand how to implement jwt in a node.js app. the security benefits and stateless nature of jwt are well-highlighted. looking forward to more detailed discussions on token expiration and handling refresh tokens. great job!

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
szalonna profile image
Joe

In my experience JWT works fine in a close, trusted system where a token could live like only for a few seconds or even minutes and each node is able to verify the tokens validity by checking the signature and using only the permissions defined in the token.
For a client-server connection where the client is outside of this trusted system (e.g. a mobile app, a browser) there should be a session-based authorization. A session can store a refresh token on the server side and each request from the client should go through an API gateway or whatever you call, which checks the session's validity and asks for a short lived access token with the refresh token and forwards the request with the token to the proper service.

The benefit of this combination is that the app can control the active sessions (e.g. you can list your logged in devices, geolocation in Google Accounts and even destroy a session if you want without even touching the device itself), you can control the length of a session independently of the refresh/access token's lifespan, you can use short lived access tokens which can be verified by the services.

If you put the token to a HTTP-only cookie, you basically use the token as a session ID, but without the benefits of a session. Yes, you can blacklist a token, but in this case your service nodes have to call back to the auth service to check if it is blacklisted or not.

Collapse
 
sillydeveloper profile image
Vitor Leitão

If it's properly done, implementing JWT is not hard.
What might be worth mentioning is that besides validating if a token is right and valid, you should have a system to be able to deactivate tokens.

Collapse
 
ariffazmi profile image
Ariff Azmi

You can implement this by using redis. Set the ttl of the token in redis. After that, before the server verify the token, you must check the token if exist in the redis, then proceed to the token validation.

Collapse
 
anna_latukhova_d87446e5ec profile image
Anna Latukhova

Exactly!

Collapse
 
vyan profile image
Vishal Yadav

Yes!

Collapse
 
bytenaija profile image
Everistus Olumese

JWT coupled with Zero Trust Access developers.cloudflare.com/cloudfla... is the way forward.

Collapse
 
yoshida_daisuke_6869c822f profile image
Yoshida Daisuke

Thanks

Collapse
 
ozzythegiant profile image
Oziel Perez

I disagree with this approach to JWT because the token is not secure and hidden from JS. The way I do it is to store it in an httponly cookie so that nothing can touch it. You will still need to persist some data to determine if a person is logged in but I think that should be just user ID and user's role. Authorization would just happen server side with the JWT from the cookie; the persisted data on the front end would just be to restrict views

Collapse
 
rishadomar profile image
Rishad Omar

Well explained thank you. My understanding is that today I should not be implementing my own authentication system. For example I would use AWS Cognito. I'm guessing what you've described is what is done in Cognito too. I would be interested in exploring further. JWT renewals. How to store on client. And how services like Cognito use it.

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
coelhoadler profile image
Adler Coelho Santos

Congratulations, great article! I have one doubt: What is the best way to store a JWT in Client Side?

Collapse
 
vyan profile image
Vishal Yadav

You can prefer to use cookie and set credentials via Cookie on browser.

Collapse
 
uneeqbox_21da38b1a9a7105c profile image
UneeqBox

Understanding JWT Authentication: A Comprehensive Guide with Examples" serves as a valuable resource for developers seeking clarity on JWT (JSON Web Token) authentication. It offers detailed explanations and practical examples, making it accessible for both beginners and experienced professionals in web development. For those interested in diving deeper into this topic or exploring related products, check out uneeqbox.com/all-product/ for more information.

Collapse
 
informatik01 profile image
Levan Kekelidze

One of the most nicest articles I have ever read!
A clear, concise and to the point explanation.
Thank you!

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
olivecyber24 profile image
Info Comment hidden by post author - thread only accessible via permalink
joseph

This is insightful...
You didn't do much.. just easy and straightforward

Collapse
 
akyno profile image
Robersom Aquino

You have my respect "Stark".

Collapse
 
rebeccapeltz profile image
Rebeccca Peltz

Good article! There are some security and scaling issues to be aware of with JWTs as this article from Redis describes. redis.io/blog/json-web-tokens-jwt-...

Collapse
 
vyan profile image
Vishal Yadav

Yeah!

Collapse
 
nevodavid profile image
Info Comment hidden by post author - thread only accessible via permalink
Nevo David

Another AI-generated article:

Image description

Collapse
 
sushantnair profile image
Sushant Nair

Can this be implemented in Django?

Collapse
 
vyan profile image
Vishal Yadav

I think Yes!

Some comments have been hidden by the post's author - find out more