JWT Authentication With Refresh Tokens
Last Updated :
07 Apr, 2025
Authentication is a critical part of web applications. Using JWT (JSON Web Tokens) for authentication is common, but adding refresh tokens provides an added layer of security and convenience. In this article, we’ll discuss how to implement JWT authentication with refresh tokens.
JWT (JSON Web Token)
JWT is a compact and URL-safe way to represent claims between two parties, typically for authentication. It’s widely used in modern web applications for securely transmitting information, such as user details.
Refresh Tokens
A refresh token is a special kind of token used to obtain a new access token after the old one expires. Refresh tokens allow you to maintain a user session without re-authenticating every time the access token expires.
Auth Persistence:
We can easily persist users between refreshes and login without any credentials. We can create a new route called refresh, whenever a token expires or a user refreshes we can get a new access token by sending a request to this route
Steps to Installation the express module:
Step 1: Run the following commands to initialize the project and create an index file & env file. (Make sure you have node and npm installed)
npm init -y
Step 2: Installing required packages
npm install express cookie-parser dotenv jsonwebtoken
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"cookie-parser": "^1.4.6",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
}
Explanation: In `index.js`, authentication logic involves creating an Express app with login and refresh routes. The login route validates credentials, responding with a refresh token and access token on a successful match, while the refresh route verifies the token for a new access token or raises an authorization error.
Example: We will now implement two routes login & refresh. The below code is for index.js:
javascript
const dotenv = require('dotenv');
const express = require('express');
const cookieparser = require('cookie-parser');
const jwt = require('jsonwebtoken')
const bodyParser = require('body-parser');
// Configuring dotenv
dotenv.config();
const app = express();
// Setting up middlewares to parse request body and cookies
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieparser());
const userCredentials = {
username: 'admin',
password: 'admin123',
email: '[email protected]'
}
app.post('/login', (req, res) => {
// Destructuring username & password from body
const { username, password } = req.body;
// Checking if credentials match
if (username === userCredentials.username &&
password === userCredentials.password) {
//creating a access token
const accessToken = jwt.sign({
username: userCredentials.username,
email: userCredentials.email
}, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '10m'
});
// Creating refresh token not that expiry of refresh
//token is greater than the access token
const refreshToken = jwt.sign({
username: userCredentials.username,
}, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '1d' });
// Assigning refresh token in http-only cookie
res.cookie('jwt', refreshToken, {
httpOnly: true,
sameSite: 'None', secure: true,
maxAge: 24 * 60 * 60 * 1000
});
return res.json({ accessToken });
}
else {
// Return unauthorized error if credentials don't match
return res.status(406).json({
message: 'Invalid credentials'
});
}
})
app.post('/refresh', (req, res) => {
if (req.cookies?.jwt) {
// Destructuring refreshToken from cookie
const refreshToken = req.cookies.jwt;
// Verifying refresh token
jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET,
(err, decoded) => {
if (err) {
// Wrong Refesh Token
return res.status(406).json({ message: 'Unauthorized' });
}
else {
// Correct token we send a new access token
const accessToken = jwt.sign({
username: userCredentials.username,
email: userCredentials.email
}, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '10m'
});
return res.json({ accessToken });
}
})
} else {
return res.status(406).json({ message: 'Unauthorized' });
}
})
app.get('/', ((req, res) => {
res.send("Server");
console.log("server running");
}))
app.listen(8000, () => {
console.log(`Server active on http://localhost:${8000}!`);
})
.env: The below code is for .env which is used to store your sensitive credentials like API keys:
PORT = 8000
ACCESS_TOKEN_SECRET=MYSECRETACCESS
REFRESH_TOKEN_SECRET=MYREFRESHTOKENSECRET
Output:
Why Use Refresh Tokens with JWT?
- Security: Access tokens are short-lived, reducing the risk of long-term exposure if compromised.
- Convenience: Refresh tokens allow for automatic re-authentication without requiring the user to log in again.
- Persistent Sessions: Refresh tokens enable long-term user sessions by renewing the access token when it expires.
Conclusion
Implementing JWT authentication with refresh tokens is a secure and efficient way to handle user sessions in web applications. By storing refresh tokens in HttpOnly cookies, you can prevent access token theft while maintaining seamless user experience. This approach ensures that your app can handle both short-lived access tokens and secure, prolonged user sessions.
Similar Reads
How to Build a React App with User Authentication?
To implement user authentication in a React app, you can use Auth0, a popular authentication service that simplifies the process of handling login, logout, and user profile management. With Auth0, you can avoid managing authentication from scratch, which saves time and ensures security. In this arti
3 min read
JWT Authentication In Node.js
In modern web development, ensuring secure and efficient user authentication is paramount. JSON Web Tokens (JWT) offer a robust solution for token-based authentication, enabling secure transmission of user information between parties. This article provides a step-by-step approach to implementing JWT
3 min read
How to Authenticate Git Push with Github Using a Token?
Git is a powerful version control system used by developers to track changes in their codebase. GitHub, a platform built around Git, allows developers to collaborate on projects and manage repositories.For years, developers have been using their GitHub username and password to authenticate Git opera
4 min read
Mastering JWT authentication in Express
While creating any application it is very important to add authentication to ensure that only authorized users can access the protected resources. AÂ JSON Web Token (JWT)Â is a JSON object utilized to securely transmit information between two parties over the web. Primarily employed in authentication
4 min read
Authentication and Authorization with OAuth
OAuth (Open Authorization) is the open standard for token-based authentication and authorization on the Internet. It can allow third-party services to exchange information without exposing the user credentials. In this article, we will guide you on how to implement the OAuth in the MERN stack applic
6 min read
How to Handle Authentication with Postman API Testing?
Authentication is very important for securing access to resources and data. When testing APIs, handling authentication correctly is important to ensure that your tests can interact with secured endpoints effectively. Postman, a popular API testing tool, provides robust features for handling various
4 min read
Multi Factor authentication using MERN
This article will guide you through creating a Multi-Factor Authentication (MFA) project using the MERN. This project aims to enhance security by implementing a multi-step authentication process. Users will be required to provide multiple forms of identification for access, adding an extra layer of
5 min read
Using JWT for user authentication in Flask
JWT (JSON Web Token) is a compact, secure, and self-contained token used for securely transmitting information between parties. It is often used for authentication and authorization in web applications. A JWT consists of three parts:Header - Contains metadata (e.g., algorithm used for signing).Paylo
6 min read
Authentication and Authorization with React Hooks
Authentication and Authorization are fundamental aspects of web development, ensuring that users have secure access to resources within an application. With the introduction of React Hooks, managing authentication and authorization in React applications has become more streamlined and efficient. In
3 min read
How To Implement JWT Authentication in Express App?
Authentication is important in web apps to make sure only the right people can access certain pages or information. It helps keep user data safe and prevents unauthorized access. Implementing JSON Web Token (JWT) authentication in an Express.js application secures routes by ensuring that only authen
6 min read