accessToken v/s refreshToken - Complete Guide to understand
In this article, we are going to discuss accessToken and refreshToken. First, we understand what are these, and then we understand the difference between them and at last, we see some practical work of these.
What are accessToken and refreshToken?
accessToken and refreshToken both are the JWT [JSON Web Token] tokens. Now you are thinking about what the JWT or JSON Web Tokens, So JWT Tokens are bearer tokens that are used to authenticate the users and share information between two parties securely. JWT Tokens consist of 3 parts separated by period [.]. These 3 parts are
Header → This part has information regarding the algorithm that is used to encrypt the data.
Payload → This is the actual data.
Signature → This is used to validate that the token is trustworthy.
Here is an example of JWT Token.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ⟹ Header
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ ⟹ Payload
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ⟹ Signature
What is the difference between accessToken and refreshToken?
accessToken | refreshToken | |
Definition | Refresh tokens are used to obtain a new access token without requiring the user to re-authenticate. | Refresh tokens are used to obtain a new access token without requiring the user to re-authenticate. |
Expired In | These will expire in less time like 1 day, 5 days, etc. | These tokens have a larger expiration time than accessToken. These will expire in 10 days, 15 day, etc. |
Saved In | These are saved in Client Cookies | These are saved in Client Cookies as well as the Database also |
Usage | These are used to access the resources without authenticating | These are used to create new access tokens |
Practical implementation
Now in this section, we are going to create a basic to understand these tokens
Install the Package
npm install jsonwebtoken express
Simple creating and applying the accessToken and refreshToken
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const secretKey = 'your-secret-key';
const accessTokenExpiry = '15m';
const refreshTokenExpiry = '7d';
// Sample user data (in a real application, this would come from a database)
const users = [
{ id: 1, username: 'user1', password: 'password1' },
{ id: 2, username: 'user2', password: 'password2' },
];
// Store refresh tokens (in-memory, for demonstration purposes)
const refreshTokens = [];
// Endpoint for user login
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Authenticate the user (in a real app, this would involve checking credentials against a database)
const user = users.find(u => u.username === username && u.password === password);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Generate access token
const accessToken = jwt.sign({ userId: user.id, username: user.username }, secretKey, { expiresIn: accessTokenExpiry });
// Generate refresh token
const refreshToken = jwt.sign({ userId: user.id }, secretKey, { expiresIn: refreshTokenExpiry });
refreshTokens.push(refreshToken);
// Return tokens to the client
res.json({ accessToken, refreshToken });
});
// Endpoint to refresh access token using refresh token
app.post('/refresh', (req, res) => {
const { refreshToken } = req.body;
// Check if refresh token is valid
if (!refreshTokens.includes(refreshToken)) {
return res.status(403).json({ error: 'Invalid refresh token' });
}
// Extract user information from refresh token
const decoded = jwt.verify(refreshToken, secretKey);
// Generate a new access token
const newAccessToken = jwt.sign({ userId: decoded.userId, username: decoded.username }, secretKey, { expiresIn: accessTokenExpiry });
// Return the new access token to the client
res.json({ accessToken: newAccessToken });
});
// Example protected endpoint
app.get('/protected', authenticateToken, (req, res) => {
res.json({ message: 'This is a protected resource.' });
});
// Middleware to authenticate access token
function authenticateToken(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
jwt.verify(token, secretKey, (err, user) => {
if (err) {
return res.status(403).json({ error: 'Invalid token' });
}
req.user = user;
next();
});
}
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
The client sends a POST request to
/login
with username and password.If credentials are valid, the server issues an access token and a refresh token.
The client can use the access token to access protected resources.
When the access token expires, the client can use the refresh token to obtain a new access token by sending a POST request to
/refresh
.The server validates the refresh token, issues a new access token, and returns it to the client.