2024-09-12
1548
Flavio Copes
3927
Sep 12, 2024 â‹… 5 min read

JWT authentication: Best practices and when to use it

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

Recent posts:

A Guide To The React UseReducer Hook

A guide to the React useReducer Hook

The useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.

Ejiro Asiuwhu
Oct 10, 2024 â‹… 13 min read
Using The Built-In SQLite Module In Node.js

Using the built-in SQLite module in Node.js

Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.

Amazing Enyichi Agu
Oct 10, 2024 â‹… 12 min read
Understanding and supporting zoom behaviors on the web

Understanding and supporting zoom behaviors on the web

Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.

Fimber Elemuwa
Oct 9, 2024 â‹… 7 min read
Comedy and tragedy masks symbolizing Playwright Extra's ability to extend Playwright with customizable plugins for both stealth and interactive browser automation tasks.

Playwright Extra: extending Playwright with plugins

Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]

Antonello Zanini
Oct 8, 2024 â‹… 9 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