2023-12-05
1678
Flavio Copes
3927
Dec 5, 2023 â‹… 5 min read

JWT authentication: Best practices and when to use it

Flavio Copes I write tutorials for developers at flaviocopes.com.

Recent posts:

This image features the Angular logo, a stylized "A" inside a red hexagon, which is positioned at the center of a geometric, abstract design. The background consists of various shades of purple and blue, overlaid with concentric circles and lines that emanate from the center, giving a sense of motion or animation. The red circles within the background also suggest movement or transitions, which could symbolize the dynamic nature of route animations discussed in the article. The image relates to the article's focus on Angular route animations, visually emphasizing the importance of transitions and movement within Angular applications. The abstract patterns and use of color gradients give a modern, tech-forward feel, aligning with the idea that animations enhance user experience by adding engagement and fluidity to user interactions within an Angular app.

Learn how to animate transitions in Angular apps

While animations may not always be the most exciting aspect for us developers, they’re essential to keep users engaged. In […]

Emmanuel Odioko
Sep 11, 2024 â‹… 9 min read

Understanding env variables and containers in Astro 4.10

Astro, renowned for its developer-friendly experience and focus on performance, has recently released a new version, 4.10. This version introduces […]

Peter Ekene Eze
Sep 10, 2024 â‹… 9 min read

Build an image editor with Fabric.js v6

In web development projects, developers typically create user interface elements with standard DOM elements. Sometimes, web developers need to create […]

Shalitha Suranga
Sep 9, 2024 â‹… 12 min read

Creating toast notifications using Solid Toast

Toast notifications are messages that appear on the screen to provide feedback to users. When users interact with the user […]

Chimezie Innocent
Sep 6, 2024 â‹… 7 min read
View all posts

21 Replies to "JWT authentication: Best practices and when to use it"

  1. I don’t understand some of the claims here.

    “Don’t store it in local storage (or session storage). If any of the third-party scripts you include in your page gets compromised, it can access all your users’ tokens.”

    Why does this matter, when you protect against CSRF with CSRF tokens?

  2. I tried storing it in cookie httpOnly but my problem is I cannot pass as request authorization header when making a request to the backend. How will this be solved?

    1. You don’t. Cookies are send with every request you make to the server, so you read from the cookie in the backend instead of the authorization header.

      1. I am thinking to store in authorization the id from db that contains the token, in authorization header the id will be used, or just encrypt all tokens with your master password then add in header, then decrypt at some point :D, really nothing seems safe

  3. After some research, yes. It’s automatically passed into the request cookies. Before I use req.headers.authorization in my middleware, now I have to use `req.cookies[‘name’]`. The idea of setting cookie as httpOnly is that you can never call it using JS to alter like localstorage.

  4. ×´ there is always the possibility that it’s intercepted and the data deciphered×´ – deciphered is not the right word here since JWT are serialised, not encrypted

  5. “the possibility that it’s intercepted and the data deciphered, exposing your user’s data.”
    We only store enough information to identify the user in the jwt token. It can be the user’s id, email, or even another access token (in case you want to implement remote logout or similar features). We don’t store sensitive data (e.g. password,…) in the token, so this should not be an issue.

    1. As http is stateless, every request made is new to server, to solve this or remember user/request, people use sessions, where server sends session id, like php sends PHPSESSID(key of cookie) stored at client side in cookie. When user makes another request php server calculate that it’s not new user. Now what if your server redirects you to the another physical server let’s say from example.net to cdn.example.org having different task assigned to them. This can cause problem because only one of the server has the power/logic to decipher that sessid right? Now that can be solved with jwt since you need only need to copy secret_key or simply .env file. And you can still verify and compare passwords

  6. I am new to JWT.
    If not through JWT how should we send sensitive data (like a password) to a server while logging in.

  7. Actually it is. If the backend gets id=1 as part of the JWT payload, then it will assume the request is made from the correctly authenticated user with id=1, and thus will complete any request made.

  8. Sending a password (either for logging in, or for creating an account) has nothing to do with JWT. JWT is about authenticating to the server after you have already sent the password. To do this correctly you must only connect via HTTPS.

  9. Hi there, nice article.
    I still have a question: if JWT is stored in cookies (secured & httpOnly), then the application is vulnerable to CSRF attacks, am I right?
    And if the JWT is stored elsewhere accessible from JS then, the app is vulnerable to XSS.
    What is the best solution?

  10. Great article. Really helped me figure out my backend authentication strategy, thanks again LogRocket!

    Recommendation: replace the terms “blacklist” and “whitelist” with “blockedlist” and “allowedlist”. I know they’re traditional terms but the racial undertones are not friendly and could be done away with 🙂

  11. There are so many issues with this article. Let’s start with the basic out of the gate. JWT is a token format. There are two common implementation uses of JWT, JWS and JWE. JWS is a signed token, JWE is an encrypted token. Use the correct JWS/JWE for what you are trying to protect.

    Next, JWT is a text string, this can be embedded in email as part of a link to not expose information, it can be placed in cookies, it can be placed HTTP headers…. How JWT is used has nothing to do with the specification.

    Next consider the fact that OAuth utilizes JWT, and this is the foundational protocol for the majority of single sign on (SSO) applications out there. If JWT was this bad, you would think one of these companies would point it out.

    If you use cookies to store the authentication data, you are susceptible to CRSF. In fact CSRF is pretty much only possible if you store the authentication data as a cookie. On the flip side, store data in local or session makes it XSS possible.

    If you want to ensure your system is secure, you really need to come at the problem from multiple directions. For web applications, using both a cookie and token in the HTTP Header with different values will provide the best protection against XSS and CSRF

    Tim

  12. Less secure? Than what?

    Storing *anything* in a cookie ? Bad reccomendation (csrf).

    Xss ? I dont see the relevance of that in this article whatsoever. Using secure http-only cookies doesn’t help against xss.

  13. is no one having issues with incognito mode? My auth flow won’t work on Chrome’s incognito mode. The cookie were the JWT is stored is completely blocked by chrome. I don’t know what todo. It’s considered third party because I set the cookie from the ‘backend’ which is hosted in a different url than the frontend. this is how i set the cookie res.cookie(‘token’, token, {
    httpOnly: true,
    secure: true,
    sameSite: ‘none’,
    partitioned: true, // I added this due to Chrome’s warning that they will block all third party cookies some time soon
    });

Leave a Reply