DEV Community

Rajat Sharma
Rajat Sharma

Posted on

Understanding Access Tokens and Refresh Tokens in Authentication

Access Tokens and Refresh Tokens in Authentication

Authentication is a crucial aspect of web applications, ensuring that users can securely access resources and perform actions. In modern web applications, Access Tokens and Refresh Tokens play a vital role in managing authentication. This article will cover what they are, how they work, and their role in secure authentication.

What Are Access Tokens and Refresh Tokens?

Access Token

An Access Token is a short-lived token used to access protected resources. It is included in API requests to authenticate the user.

  • Typically, an access token is a JWT (JSON Web Token).
  • It contains user-related data such as user ID, role, and expiration time.
  • Stored client-side, usually in memory or local storage.
  • Valid for a short period (e.g., 15 minutes to 1 hour).
  • Once expired, it cannot be used to make API requests.

Refresh Token

A Refresh Token is a long-lived token used to obtain a new access token without requiring the user to log in again.

  • It is issued alongside the access token when the user logs in.
  • It is stored securely (HTTP-only cookie or database).
  • Used when the access token expires to obtain a new access token.
  • Has a longer expiration time (e.g., 7 days or more).
  • Prevents the need for frequent re-authentication.

How Access Token and Refresh Token Work

The authentication flow typically follows these steps:

  1. User logs in using their credentials.
  2. The server validates the credentials and issues:
    • An Access Token (short-lived, used for API requests).
    • A Refresh Token (long-lived, used to get new access tokens).
  3. The Access Token is included in API requests (e.g., via Authorization: Bearer <token> header).
  4. When the Access Token expires, the client sends the Refresh Token to the server to get a new Access Token.
  5. The server verifies the Refresh Token, issues a new Access Token, and updates the Refresh Token if necessary.
  6. If the Refresh Token is invalid or expired, the user is required to log in again.

Generating Access and Refresh Tokens in Node.js

In a Node.js backend (e.g., Express.js), you can generate JWTs using the jsonwebtoken package.

Install JSON Web Token (JWT) package:

npm install jsonwebtoken
Enter fullscreen mode Exit fullscreen mode

Generate Access and Refresh Tokens:

import jwt from "jsonwebtoken";

const generateTokens = (userId) => {
  const accessToken = jwt.sign(
    { _id: userId },
    process.env.ACCESS_TOKEN_SECRET,
    { expiresIn: "15m" }
  );

  const refreshToken = jwt.sign(
    { _id: userId },
    process.env.REFRESH_TOKEN_SECRET,
    { expiresIn: "7d" }
  );

  return { accessToken, refreshToken };
};
Enter fullscreen mode Exit fullscreen mode

Storing Tokens Securely

  • Access Token: Store in memory or secure HTTP headers (avoid local storage to prevent XSS attacks).
  • Refresh Token: Store in HTTP-only, secure cookies or databases to prevent theft.

Refreshing Access Token API

const refreshAccessToken = async (req, res) => {
  const incomingRefreshToken = req.cookies.refreshToken;
  if (!incomingRefreshToken) {
    return res.status(401).json({ message: "Unauthorized request" });
  }

  try {
    const decoded = jwt.verify(incomingRefreshToken, process.env.REFRESH_TOKEN_SECRET);
    const newAccessToken = jwt.sign(
      { _id: decoded._id },
      process.env.ACCESS_TOKEN_SECRET,
      { expiresIn: "15m" }
    );

    res.json({ accessToken: newAccessToken });
  } catch (error) {
    res.status(403).json({ message: "Invalid refresh token" });
  }
};
Enter fullscreen mode Exit fullscreen mode

Access Token vs. Session Authentication

Feature Access Token + Refresh Token Session Authentication
Stateless ✅ Yes ❌ No (Stored in DB)
Secure from XSS ✅ Yes (if HTTP-only) ❌ No (If stored in local storage)
Scaling ✅ Easy ❌ Hard (Session storage needed)
Performance ✅ Fast ❌ Can slow down with DB lookups
Token Expiry ✅ Yes ❌ No (Session persists)

Conclusion

Access Tokens and Refresh Tokens provide a scalable and secure way to manage authentication in web applications. By using them properly, you can ensure seamless user experiences while maintaining security best practices.


💡 If you found this article helpful, feel free to share your thoughts in the comments below! 🚀

Top comments (0)