September 30, 20247 min readPublished on Hashnode

Implementing JWT-Based Authentication

Implementing JWT-Based Authentication

Before jumping into implementation, let's take a step back and understand what we're actually dealing with.

Imagine you've logged into an application.

You enter your email and password, the server verifies them, and suddenly you're authenticated. But there's a problem:

How does the server remember that you're logged in when you make your next request?

One way is to keep a session on the server and give the browser a session ID. But JWT takes a different approach.

Instead of making the server remember the authentication state, we can give the client a signed token that carries information about the user.

That token is called a JSON Web Token (JWT).

A JWT is essentially a compact, URL safe string that can carry claims (pieces of information about a user or a requestand) is cryptographically signed so that the server can verify that the token hasn't been modified.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30

At first glance, it looks like one long random string.

But it isn't.

A JWT is made up of three separate parts:

Header.Payload.Signature

Let's break them down...

Header : "How should this token be verified?"

It contains metadata about the token, most importantly the algorithm used to create its signature.

For example: { "alg": "HS256", "typ": "JWT" }

alg tells us which signing algorithm is being used. typ tells us that this is a JWT.

Payload: "Who is this token about?"

This is where JWT stores its claims.

For example:

{ "sub": "123", "role": "admin", "iat": 1726483200, "exp": 1726486800 }

These claims can contain information such as:

User ID, Roles, Permissions, Token expiration time, Issuer, Audience

sub commonly represents the subject of the token, while exp represents its expiration time.

But there's one important thing to understand:

The payload is not encrypted by default.

Anyone who has the token can decode the Header and Payload.

So don't put sensitive information such as passwords, API keys, or private data inside a JWT payload just because it is "encoded."

JWT gives us integrity and authenticity through signing, not confidentiality.

Signature: "Has someone tampered with this token?"

Suppose the client receives a JWT containing:

{ "sub": "123", "role": "user" }

What stops the client from changing it to:

{ "sub": "123", "role": "admin" }

This is where the signature comes in.

The server takes the encoded Header and Payload and signs them using a secret key (for HMAC algorithms such as HS256).

Conceptually, it looks like this:

HMAC( base64url(header) + "." + base64url(payload), secret )

So when the client sends this token back to the server, the server can verify the signature.

If someone changes the payload the signature will no longer match.

The server can therefore detect that the token has been modified and reject it.

But there's another problem!!!

Imagine we give a user a JWT when they log in and make that token valid for 30 days.

That sounds convenient. The user doesn't have to log in again for a month.

But the problem there's that if that token gets stolen, whoever has it can potentially use it for the next 30 days.

So instead of having one long-lived token, we can split the responsibility between two tokens:

  • Access Token - used frequently to access protected resources.

  • Refresh Token - used occasionally to obtain a new access token.

Think of it like a hotel.

The access token is your room key.

You use it whenever you want to enter your room.

The refresh token is more like the document you use at the reception desk to get a new room key when the old one expires.

You don't carry the refresh token into every room.

You only use it when you need a new access token.

Access Token: The short-lived pass

The access token is the token your application uses to access protected APIs.

For example:

BASH
GET /api/profile
Authorization: Bearer

The server receives the token and verifies its signature.

If the signature is valid and the token hasn't expired, the server can trust the claims inside it and process the request.

A simple access token might be generated like this:

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

Notice that we're using a separate secret for the access token.

Why make it short-lived? Because if an access token is stolen, its useful lifetime is limited.

But now we have a new problem.

Does the user have to log in every 15 minutes?

Obviously, that would be a terrible user experience.

That's where the refresh token comes in.

Refresh Token — The ticket for a new access token

A refresh token has a much longer lifetime.

Its job isn't to access your application's APIs directly.

Its job is to say:

"The user already authenticated. Give them a new access token."

For example:

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

What actually happens when the user logs in?

Client -- (email + password) --> Server -- (verify password, generate Access Token & Refresh Token) --> Client(Access Token)

So after generating the token server stores the Refresh Token in Database and send the Access Token to the client along with the request.

Now the user starts making requests

Client send the Access Token along with the request.

Server verify signature, check expiry, and read user ID.

NOTE: The server doesn't store the Access Token, it just verify the token signature.

JAVASCRIPT
const decoded = jwt.verify( accessToken,         process.env.ACCESS_TOKEN_SECRET ); 

console.log(decoded.userId);

If verification succeeds, the request can continue.

But eventually... the Access Token expires

Let's say the access token was valid for 15 minutes. We don't want to send them back to the login page.

Instead, the client calls a dedicated refresh endpoint:

HTML
POST /auth/refresh-token

The client sends the refresh token along with the request.

The server then verifies it:

JAVASCRIPT
const decoded = jwt.verify( refreshToken,                               process.env.REFRESH_TOKEN_SECRET );

If the refresh token is valid, the server knows that the session can continue.

It generates a new access token and send it to the client. The client receives the new access token and continues making API requests.

So from the user's perspective: Nothing happened. They stayed logged in.

But why store the Refresh Token?

There's an important security difference here.

An access token can often be verified completely through its signature and expiration.

A refresh token, however, is much more powerful because it can be exchanged for new access tokens.

So many applications keep track of refresh tokens server-side.

During refresh, the server can verify both:

  1. Is the JWT signature valid?

  2. Does this refresh token match the one stored for the user?

This gives the server a way to revoke a refresh token.

A small refresh endpoint

JAVASCRIPT
const refreshAccessToken = async (req, res) => {
  const refreshToken = req.cookies.refreshToken;

  if (!refreshToken) {
    return res.status(401).json({
      message: "Refresh token required",
    });
  }

  try {
    const decoded = jwt.verify(
      refreshToken,
      process.env.REFRESH_TOKEN_SECRET
    );

    const user = await User.findById(decoded.userId);

    if (!user || user.refreshToken !== refreshToken) {
      return res.status(403).json({
        message: "Invalid refresh token",
      });
    }

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

    return res
      .cookie("accessToken", accessToken, {
        httpOnly: true,
        secure: true,
        sameSite: "strict",
      })
      .json({
        message: "Access token refreshed",
      });
  } catch {
    return res.status(403).json({
      message: "Invalid or expired refresh token",
    });
  }
};

The interesting thing here is that the refresh endpoint doesn't need the old access token.

It only needs a valid refresh token.