Skip to main content

Command Palette

Search for a command to run...

Access Token And Refresh Token in JWT(Json Web Token)

Published
2 min read
Access Token And Refresh Token in JWT(Json Web Token)

In context of JWT authentication, Access Token and Refresh Token serve distinct function to manage secure session and user authentication efficiently.

Access Token:

  • Access token is a shot-lived credential.

  • With this token user can access protected resources (like api endpoints) without repeated login.

Refresh Token:

  • Refresh token is used to obtain new access token after the original one expires, extending the session without requiring user to login again.

  • Refresh token are long lived, often lasting days or weeks

Why Use Both?

  • Security: By limiting access tokens to a short lifespan, the risk associated with a stolen token is reduced.

  • Convenience: The refresh token avoids frequent logins, as the user can get new access tokens without re-authenticating.

npm install jsonwebtoken

Generate an access token

const jwt = require('jsonwebtoken');

const secretKey = 'your_secret_key'; // Replace with a secure, unique key
const payload = {
  userId: '12345', // Add user information or claims here
  role: 'user'     // You can add custom claims like role, permissions, etc.
};

// Function to generate an access token
function generateAccessToken(user) {
  return jwt.sign(user, secretKey, { expiresIn: '15m' }); // Token expires in 15 minutes
}

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

Verify the access token

// Function to verify the access token
function verifyAccessToken(token) {
  try {
    const decoded = jwt.verify(token, secretKey);
    console.log('Token is valid:', decoded);
    return decoded; // Return decoded data if needed
  } catch (err) {
    console.log('Token is invalid:', err.message);
    return null;
  }
}

verifyAccessToken(accessToken);
P

Nice Blog, try to write more detailed ones

A

great!

1
A

Thank you bhai

H

its good

1
A

Thanks for your feedback! Tell me if you want more content like this