Skip to main content

Command Palette

Search for a command to run...

Access Token vs Refresh Token: Understanding the Key Differences

The Role of Access and Refresh Tokens in Modern Authentication

Published
•3 min read
Access Token vs Refresh Token: Understanding the Key Differences
A

👋 Hi there! I’m a passionate developer from Lahore, Punjab, Pakistan, Hand in the MERN stack. With a knack for creating dynamic and responsive web applications, I love turning ideas into reality through code.

Access Token

An Access Token is a short-lived credential used to authenticate and authorize a user’s access to specific resources, such as APIs or services. It’s issued by an authorization server after a successful authentication and is typically included in HTTP requests to prove the user’s identity and permissions.

This code is a middleware function in a Node.js application that checks if a JSON Web Token (JWT) is valid to ensure the user making the request is authenticated. If the token is valid, the middleware gets the user from the database, attaches the user information to the request object, and lets the request continue to the next middleware or route handler. If the token is invalid or missing, an error is thrown, and the request is denied.

  • The middleware attempts to retrieve the JWT from two possible sources:

    • req.cookies?.accessToken: If the token is stored in a cookie named accessToken.

    • req.header("Authorization")?.replace("Bearer ", ""): If the token is passed in the Authorization header as a Bearer token (e.g., Bearer <token>).

  • If no token is found, an error is thrown with a 401 status, indicating an "Unauthorized request."

This code is a method defined on a Mongoose schema that generates a JSON Web Token (JWT) for a user. The JWT is a compact, URL-safe token that contains user information (the payload) and is signed with a secret key. This token is used to authenticate users in a web application, typically for a limited period defined by the expiresIn property.

Refresh Token

This code is an asynchronous handler function that refreshes an access token using a provided refresh token. When the refresh token is valid, a new access token and refresh token are generated and sent to the client. If the refresh token is invalid or expired, appropriate error responses are provided.

  • The function refreshAccessToken begins by retrieving the refresh token from two possible sources

  • req.cookie.refreshToken: The refresh token might be stored in a cookie.

  • req.body.refreshToken: Alternatively, it might be included in the request body.

  • If no refresh token is found, an ApiError is thrown with a 400 status code, indicating an "Unauthorized Request.

  • The function uses jwt.verify() to verify the validity of the incoming refresh token using the secret key process.env.REFRESH_TOKEN_SECRET.

  • If the token cannot be verified, an ApiError is thrown with a 400 status code, indicating an "Invalid Refresh Token.

  • The decoded token contains the user's ID, which is used to find the user in the database using User.findById(decodedToken?._id)

  • The function checks if the provided refresh token matches the one stored in the user’s document (user?.refreshToken).

  • The genrateAccessAndRefreshtoken function is called to generate a new access token and a new refresh token for the user (user._id).

  • The new tokens are returned by this function.

This will defines a method in a Mongoose schema for generating a JSON Web Token (JWT) specifically used as a refresh token. The refresh token is a long-lived credential that allows clients to obtain a new access token without re-authenticating.


Keep your applications secure with the latest in JWT best practices

This article explores the concepts and implementation details of Access Tokens and Refresh Tokens in a Node.js application. It covers the use of middleware to validate JSON Web Tokens (JWTs) for user authentication, methods to generate JWTs using Mongoose schemas, and a handler function for refreshing access tokens using refresh tokens. The focus is on ensuring secure token management and authentication practices.