Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

Where jwt token is stored?

4 Answer(s) Available
Answer # 1 #

In this JWT authentication tutorial, you’ll learn when to use JWT, why you shouldn’t use JWT for sessions, and how to store JWTs in cookies to prevent security issues. We’ll also go over some general JWT best practices.

Here’s what we’ll cover:

JSON Web Tokens (JWT) is a JSON-encoded representation of a claim or claims that can be transferred between two parties.

Though it’s a very popular technology, JWT authentication comes with its share of controversy. Some say you should never use it. Others say JWT authentication is amazing.

The truth lies somewhere in between: the value of using JWT depends on your use case and project requirements.

Before we dig any deeper, let’s briefly review what JWT authentication is.

A JWT is a mechanism to verify the owner of some JSON data. It’s an encoded, URL-safe string that can contain an unlimited amount of data (unlike a cookie) and is cryptographically signed.

When a server receives a JWT, it can guarantee the data it contains can be trusted because it’s signed by the source. No middleman can modify a JWT once it’s sent.

It’s important to note that a JWT guarantees data ownership but not encryption. The JSON data you store into a JWT can be seen by anyone that intercepts the token because it’s just serialized, not encrypted.

For this reason, it’s highly recommended to use HTTPS with JWTs (and HTTPS in general, by the way).

We’re not going to cover how JWTs are generated in detail. For an in-depth, up-to-date look at how JWT authentication works, check out “JWT authentication from scratch with Vue.js and Node.js.”

JWT is a particularly useful technology for API authentication and server-to-server authorization.

For a comprehensive guide on using JWT technology to authenticate APIs, check out “How to secure a REST API using JWT.”

On the other hand, you should not use JWTs as session tokens by default. For one thing, JWT has a wide range of features and a large scope, which increases the potential for mistakes, either by library authors or users.

Another issue is that you can’t remove a JWT at the end of a session because it’s self-contained and there’s no central authority to invalidate them.

Finally, to put it simply, JWTs are relatively large. When used with cookies, this adds up to a ton of overhead per request.

Using JWTs for session tokens might seem like a good idea at first because:

Ultimately, if you already have a database for your application, just use a sessions table and use regular sessions as provided by the server-side framework of choice.

Why? There is a cost involved in using JWTs: they are sent for every request to the server and it’s always a high cost compared to server-side sessions.

Also, while the security risks are minimized sending JWTs using HTTPS, there is always the possibility that it’s intercepted and the data deciphered, exposing your user’s data.

A very common use for JWT — and perhaps the only good one — is as an API authentication mechanism.

JWT technology is so popular and widely used that Google uses it to let you authenticate to its APIs.

The idea is simple: you get a secret token from the service when you set up the API:

On the client side, you create the token (there are many libraries for this) using the secret token to sign it.

When you pass it as part of the API request, the server will know it’s that specific client because the request is signed with its unique identifier:

How do you invalidate a single token? A no-effort solution is to change the server secret key, which invalidates all tokens. However, this is not ideal for users, who may have their tokens expired for no reason.

One way to do it is to add a property to your user object in the server database to reference the date and time at which the token was created.

A token automatically stores this value in the iat property. Every time you check the token, you can compare its iat value with the server-side user property.

To invalidate the token, just update the server-side value. If iat is older than this, you can reject the token.

Another way to achieve this is by establishing a blocklist in your database cached in memory (or, even better, an allowlist).

A JWT needs to be stored in a safe place inside the user’s browser. If you store it inside localStorage, it’s accessible by any script inside your page. This is as bad as it sounds; an XSS attack could give an external attacker access to the token.

To reiterate, whatever you do, don’t store a JWT in local storage (or session storage). If any of the third-party scripts you include in your page is compromised, it can access all your users’ tokens.

To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that’s only sent in HTTP requests to the server. It’s never accessible (both for reading or writing) from JavaScript running in the browser.

JWTs can be used as an authentication mechanism that does not require a database. The server can avoid using a database because the data store in the JWT sent to the client is safe.

Say you have one server where you are logged in, SERVER1, which redirects you to another server SERVER2 to perform some kind of operation.

SERVER1 can issue you a JWT that authorizes you to SERVER2. Those two servers don’t need to share a session or anything to authenticate you. The token is perfect for this use case.

How do you decide which JWT library to use in your project? A good place to start is this list of JWT libraries for token signing and verification.

The site contains a list of the most popular libraries that implement JWT, including libraries for Node.js, Python, Rust, Go, JavaScript, and many more.

Select your language of choice and pick the library that you prefer — ideally, the one with the highest number of green checks.

JWT is a very popular standard you can use to trust requests by using signatures, and exchange information between parties. Make sure you know when it’s best used, when it’s best to use something else, and how to prevent the most basic security issues.

[4]
Edit
Query
Report
Myron Chabot
Bookbinder
Answer # 2 #

Token-based authentication (most often JWT based) is referred to as stateless authentication — because the authentication server doesn’t need to maintain any state, the token itself contains all the necessary information to verify a token bearer’s authentication.

The server can seamlessly check whether the JWT contains the necessary information about the user’s identity and authorization to perform an action without querying the database. Now the question arises, if such is the scenario then do we need to save the JWT token in the database? If yes, then when and why?

I will try to cover three scenarios where the necessity to save the tokens in DB arises.

Before we dive deep into the topic let me give you a tiny introduction on access tokens and refresh tokens. When a user logs in, the authorization server issues an access token (generally JWT), then the client can use this token to make secure API calls.

When the client needs to access any protected resource from the server on behalf of a user, it attaches the token in the request header which helps the server to determine the authenticity of the client/user. Access tokens have a very short lifespan (generally not more than 30mins).

Once the access token expires the client application can prompt the user to re-login (which is certainly not a good user experience) or the client can use a refresh token which is issued by the authorization/authentication server to generate a new access token.

Refresh tokens generally have a much higher life span than the access tokens. They may or may not be JWT. Refresh tokens can be a simple encoded string or a UUID. Refresh tokens are also bearer tokens, hence ​malicious users can theoretically steal the refresh token and use it indefinitely to access protected resources from the server. Then how do we secure our application from malicious users accessing protected resources?

The most straightforward answer to this question would be saving refresh tokens in the database and revoking access of all users by deleting all the refresh tokens when any such malicious behavior is reported. But what if it’s not reported, do we let the malicious user access protected resources indefinitely? Do we keep on saving refresh tokens in our database?

The answer to this question is refresh token rotation, refresh token reuse detection and deleting all old refresh tokens when a new one is generated. Let me try to explain my answer — when a new access token is generated (at the time of sign in/signup or using a refresh token) — a new refresh token should also be generated (this is called refresh token rotation), and all the previous refresh tokens must be deleted.

In this way — even if a malicious user steals the refresh token, when the legitimate user tries to log in to the application, a new access token and a new refresh token will be generated, and all other refresh tokens will be deleted, if the malicious user tries to use the old refresh token the refresh token reuse detection would already detect the reuse or the refresh token wouldn’t exist in DB. This way we can prevent a malicious attack.

A verification email is sent out to a user email address (which he/she uses to register), after they register into an application. This email contains a link with a token generated by the server for that user ID, when the user clicks on the link an API request is made to the server with this token (email verification token). These tokens always have a short expiration time.

The server needs to verify this token for that user email. But what if the user clicks on the resend verification email again even before the current link/token’s expiration? To handle such scenarios tokens need to be saved in DB — either all the tokens or only the latest one (when a new token is generated old tokens are deleted).

Since all or more than one token is active at this moment, JWT verification would pass for any of the tokens, but we should compare only with the latest one. Once verification is done, all the email verification tokens for that user must be deleted.

When a user clicks on forgot-password and enters his/her email address, an email is sent out to the user containing a link (which contains a reset password token). These reset password tokens also generally have a short lifespan.

Once a user clicks on the link, he/she needs to enter the new password, and once clicked on reset password an API request is made to the server containing the new password and token sent in the email link. The reason to save/not save this token is pretty similar to email-verification-token. If the user clicks on the forget password more than once and receives multiple emails (all before the token’s expiry).

In this case, we need to store all the tokens in DB or the latest one (when a new token is generated the old tokens should be deleted). After a user clicks on the link, the token in the API request payload is matched with the latest token in DB for that user, and all the reset-password tokens for that user must be deleted.

[4]
Edit
Query
Report
Banksy Koster
Soloist
Answer # 3 #

A JWT needs to be stored in a safe place inside the user's browser. Any way,you shouldn't store a JWT in local storage (or session storage). If you store it in a LocalStorage/SessionStorage then it can be easily grabbed by an XSS attack.

[4]
Edit
Query
Report
Shahid pzkmkmeb
CHIEF COMPUTER PROGRAMMER
Answer # 4 #

I have been designing and developing web applications for more than 7 years.

Through these years, I have been seen a lot of authentication mechanisms, some of them are RESTful and others are not. The RESTful services mostly used JSON Web Token (JWT) as an authentication token.

Whenever I implemented JWT-based authentication, I asked myself this question, “Where do we store the JWT?”

Edit: This article is focusing only on browser implementation.

Let’s answer the big question.

We have three options available for storing the data on the client side and each of those has its own advantages and disadvantages. And the options are:

If you set the JWT on cookie, the browser will automatically send the token along with the URL for the Same Site Request. But it is vulnerable to the CSRF.

We can protect the site against CSRF by setting a cookie with SameSite=strict

Edit 1: I̶n̶ ̶g̶e̶n̶e̶r̶a̶l̶ ̶p̶e̶o̶p̶l̶e̶ ̶m̶i̶g̶h̶t̶ ̶t̶h̶i̶n̶k̶,̶ ̶X̶S̶S̶ ̶c̶a̶n̶ ̶b̶e̶ ̶d̶e̶f̶e̶a̶t̶e̶d̶ ̶i̶f̶ ̶w̶e̶ ̶s̶e̶t̶ ̶t̶h̶e̶ ̶h̶t̶t̶p̶O̶n̶l̶y̶ ̶f̶l̶a̶g̶,̶ ̶b̶u̶t̶ ̶i̶t̶ ̶i̶s̶ ̶p̶o̶s̶s̶i̶b̶l̶e̶ ̶t̶o̶ ̶a̶t̶t̶a̶c̶k̶ ̶b̶y̶ ̶u̶s̶i̶n̶g̶ ̶X̶S̶T̶ ̶”̶s̶u̶b̶s̶e̶t̶”̶ ̶(̶k̶i̶n̶d̶a̶)̶ ̶o̶f̶ ̶X̶S̶S̶.̶

Edit 2: We can easily defect the XSS by setting httpOnly flag.

Pros:

Con:

localStorage

The localStorage doesn’t send the data automatically along with the URL. So you need to implement the system for the auth token for every URL. But the best part is that this method is not vulnerable to CSRF.

Pros

Con

Session Storage

Session Storage is pretty much the same as Local Storage, except the token will accessible only one tab, once the tab is closed the session got destroyed. So it not useful for the feature like remember me. But this can be used in the multi-login feature like Tab A is in a different login and Tab B is in different login.

Pros:

Con:

You might notice that all the 3 methods have the same con — “Vulnerable to XSS”. Yes, all these methods are vulnerable to XSS. Please do care about XSS and always follows the best practices for XSS protection.

Both localStorage and SessionStorage are not protected by the XSS by default.

[3]
Edit
Query
Report
Sakina Santiago-Hudson
Chief Creative Officer