DEV Community

Cover image for JWT Access Tokens & Refresh Tokens
Swapnil Sagar
Swapnil Sagar

Posted on

JWT Access Tokens & Refresh Tokens

Access tokens and refresh tokens are integral components of the JSON Web Token (JWT) authentication mechanism. Let's break down their concepts:

Access Token:
An access token is a digitally signed and encoded token that is issued by an authentication server to a client application after successful authentication. It represents the authorization granted to the client to access protected resources or perform specific actions on behalf of an authenticated user. The access token contains claims such as user identification, expiration time, and scope.
Once a client receives an access token, it includes it in the Authorization header or sends it as a parameter in API requests to the server. The server then verifies the token's authenticity and checks its claims to ensure the requested action is permitted for the authenticated user.

Access tokens typically have a relatively short expiration time, such as a few minutes or hours, to ensure security. When an access token expires, the client needs to obtain a new one to continue accessing protected resources.

Refresh Token:
A refresh token is a long-lived credential that is also issued alongside the access token during the authentication process. While the access token provides temporary access, the refresh token serves as a means to obtain new access tokens without re-authenticating the user.
When the access token expires, the client can send the refresh token to a token endpoint or authorization server. The server verifies the refresh token's validity, and if it is valid, issues a new access token. The client replaces the expired access token with the new one and continues accessing resources seamlessly.

Refresh tokens have a longer expiration time compared to access tokens, which can range from days to months. They are typically securely stored on the client-side and transmitted over secure channels to prevent unauthorized access.

The use of refresh tokens enhances security by minimizing the time an access token is active, reducing the risk of token interception and misuse. It also provides a smoother user experience since the user doesn't need to re-enter their credentials frequently.

It's important to note that the implementation details of access and refresh tokens can vary depending on the authentication framework or service being used, but the core concepts remain consistent.

import jwt from 'jsonwebtoken';

// Function to generate an access token
function generateAccessToken(userId) {
  const payload = {
    userId: userId,
    exp: Math.floor(Date.now() / 1000) + 15 * 60, // Token expires in 15 minutes
  };
  const accessToken = jwt.sign(payload, 'your-secret-key');
  return accessToken;
}

// Function to generate a refresh token
function generateRefreshToken(userId) {
  const payload = {
    userId: userId,
    exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // Token expires in 30 days
  };
  const refreshToken = jwt.sign(payload, 'your-secret-key');
  return refreshToken;
}

// Example usage
const userId = 123;

const accessToken = generateAccessToken(userId);
console.log('Access Token:', accessToken);

const refreshToken = generateRefreshToken(userId);
console.log('Refresh Token:', refreshToken);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)