DEV Community

Jaligama Satyaveer
Jaligama Satyaveer

Posted on

1 2 1

How Token-Based Authentication Works: A Practical Walkthrough

Authentication is essential for securing web applications. In this article, I will explain token-based authentication using a real-world example of a login system built with React, Node.js, and MongoDB. If you're new to this, don't worry! I’ll guide you step by step.

How Does Token-Based Authentication Work?
Imagine you’re logging into an app. Here’s what happens behind the scenes:

  1. You register an account by entering your email/phone, name, and password.
  2. You log in by providing your email/phone and password.
  3. If your credentials are correct, a token is generated and sent to your device.
  4. Every time you access a protected page, your token is checked to verify your identity.
  5. If the token is valid, you can proceed. If not, you’ll be asked to log in again.

This token acts like a temporary digital key, allowing access without needing to log in repeatedly.

Step 1: User Registration

When signing up, you provide details like your email/phone, name, and password. Your password is securely stored in the database using a method called hashing.

  • If your email or phone number is already registered, you’ll get an error message.
  • If everything is correct, your account is created, and you can log in.

Once registered, you can move to the login step.

Step 2: Logging In and Token Generation

When you log in:

  1. Your credentials are sent to the server.
  2. The server checks if the email/phone exists in the database.
  3. If the user exists, it compares your entered password with the stored password.
  4. If the password is correct, the server generates a JWT token and sends it back.

Code for Token Generation (Backend)

const token = jwt.sign(
  { userId: existingUser._id },
  process.env.JWT_SECRET_KEY!,
  { expiresIn: "15s" } // Token expires in 15 seconds
);
Enter fullscreen mode Exit fullscreen mode

This token contains the user's ID and has an expiration time (15 seconds in this example, but in real-world apps, it is much longer).

Once received, the token is stored in the browser so the user doesn’t have to log in again immediately.

Step 3: Accessing a Protected Page

Now that you're logged in, you want to access a protected page (like your profile or dashboard). Here’s how it works:

  1. You click on a button (e.g., "View Profile").
  2. Your browser attaches the token to the request.
  3. The server checks if the token is valid.
  4. If the token is valid, the server allows access.
  5. If the token is missing, invalid, or expired, the server denies access and redirects you to the login page.

Code for Token Validation (Backend)

const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token) {
    return res.status(401).json({ message: "Unauthorized" });
  }
  try {
    const decodedToken = jwt.verify(token, process.env.JWT_SECRET_KEY!);
    req.user = decodedToken.userId;
    next();
  } catch (err) {
    return res.status(401).json({ message: "Unauthorized" });
  }
};
Enter fullscreen mode Exit fullscreen mode

If the token is valid, you can access the page. Otherwise, you’re redirected to log in again.

Step 4: What Happens When the Token Expires?

Tokens are temporary for security reasons. When a token expires:

  • Your next request will be rejected with a 401 (Unauthorized) error.
  • You will be redirected to the login page to re-authenticate.

This ensures that only active users can access protected data.

Video

Repo Links

Frontend
Backend

Wrapping up

Token-based authentication is a modern and secure way to manage user sessions in web applications. Applications become more secure, scalable, and efficient, ensuring a smooth user experience while protecting sensitive data.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (1)

Collapse
 
champsoft profile image
champsoft

Great breakdown of token-based authentication! The step-by-step guide with React, Node.js, and MongoDB makes it super clear. Love how you explained token expiration for added security. Very helpful post!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay