DEV Community

Cover image for Refresh Token implementation in nodejs with typescript
Chafroud Tarek
Chafroud Tarek

Posted on

Refresh Token implementation in nodejs with typescript

Refresh tokens are a key component of modern web application authentication and authorization. They allow users to continue accessing protected resources even after their initial access token has expired, without requiring them to re-enter their credentials. In this tutorial, we will learn how to implement refresh tokens in a Node.js application using TypeScript.

We will start by setting up a basic Node.js server and installing the necessary dependencies. Then, we will configure our server to issue refresh tokens to authenticated users, and implement a route that allows them to exchange their refresh token for a new access token.

By the end of this tutorial, you will have a solid understanding of how refresh tokens work and how to implement them in a Node.js application using TypeScript. Let's get started!

👋 You can also check my weekly posts in Linkedin

Requirements

  • Basic knowledge of nodejs/expressjs.
  • Basic Knowledge of typescript.
  • Basic Knowledge of sequelize.

To begin, we will be using a pre-configured repository that includes all necessary packages, routes, controllers, models, and other components needed for implementing refresh tokens in a Node.js application using TypeScript. This will save us time and allow us to focus on the important task of implementing refresh token functionality.

👉 Starter

1️⃣ we will set up two controllers: register and getLoggedInUser. These controllers will handle the logic for retrieving the logged in user and creating new user accounts, respectively. Let's begin by implementing these controllers.

▪️Register controller:

register
▪️Register Errors:

Image description

▪️Register result:

Register error

▪️getLoggenInUser controller:

getLoggenInUser

▪️getLoggenInUser result:

Image description

2️⃣ Before we can proceed to the login controller, we need to create a refresh token model that will store the user's refresh token, email, and expiry date. This information will be used later on in the refresh token controller to verify the validity of the refresh token.

like this:

refresh Models

3️⃣ In addition to the refresh token model, we also need to create two functions: "verifyExpiration" and "createRefreshToken." The "verifyExpiration" function will be used to check the expiry date of the refresh token, while the "createRefreshToken" function will generate a new refresh token. These functions can be found in the file located at src/utils/.

utils

4️⃣ Once we have completed the creation of the refresh token model and the necessary functions, we can proceed to the implementation of the login controller.
" The important part is to set the refresh token in the cookies of the response object and then send the response back to the client. This ensures that the refresh token is stored on the client's device and can be used later to request a new access token ".

login controller

▪️ result:

Image description

▪️ Cookies:

Image description

5️⃣ Next, we will create a refresh controller that will verify the validity of the refresh token and generate a new access token if it is valid.

refreshToken

▪️ result:

Image description

👉 final result

To sum up, refresh tokens are a valuable resource for preserving both the security and convenience of an application. By enabling users to remain logged in despite the expiration of their access tokens, refresh tokens help to enhance the user experience. By following the instructions outlined in this blog, you can easily incorporate refresh tokens into your Node.js application and provide a secure and seamless user experience.

Top comments (6)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

No token must be saved to a database. It is a security risk. Ideally, you just emit a token and never record it anywhere.

Collapse
 
fjones profile image
FJones • Edited

No access token should be saved to a database. That's not what's happening here, though. Refresh tokens (when properly implemented) should live in the database: That is how you detect and invalidate token hijacking - because refresh tokens should be single use, single purpose tokens that exist solely to generate a new access token exactly once. In addition, they should (aside from explicit authentication) be the only way to generate a new access token - i.e. no refresh with just an access token.

That means that you can do nice things like invalidating all refresh and access tokens in that token chain when an attempt to reuse the refresh token is detected. This does, however, also come with the recommendation of keeping access token lifetimes very low.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Agreed about the single use case (token rotation), but for that it is best to assign an ID to the token and only save the ID. If user X logs in now, and receives an access token useful for 5 minutes plus a refresh token, then during a 5 minute window you could be hacked and the refresh token stolen from the DB. Having any actual token in the database is high risk. You don't even need a hacker. A disgruntled DBA will do the harm just as easily.

Collapse
 
chafroudtarek profile image
Chafroud Tarek

Thank you for your feedback. You are correct that it is generally a security risk to save tokens, including refresh tokens, to a database. I completely agree that the security of our users' data is a top priority. While this blog post serves as a sample explanation of how to implement refresh tokens. Your feedback gave me inspiration to consider additional security measures for the next blog post. inshallah

Collapse
 
thi3rry profile image
Thierry Poinot

What about invalidation ? Or a way to force token expiration ?

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Glad you asked.

Invalidating JSON Web Tokens (JWT) the Right Way
Invalidating JSON Web Tokens (JWT): NodeJS + Express

I am still owing to that series the example for ASP.Net, but as described.