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:
- You register an account by entering your email/phone, name, and password.
- You log in by providing your email/phone and password.
- If your credentials are correct, a token is generated and sent to your device.
- Every time you access a protected page, your token is checked to verify your identity.
- 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:
- Your credentials are sent to the server.
- The server checks if the email/phone exists in the database.
- If the user exists, it compares your entered password with the stored password.
- 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
);
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:
- You click on a button (e.g., "View Profile").
- Your browser attaches the token to the request.
- The server checks if the token is valid.
- If the token is valid, the server allows access.
- 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" });
}
};
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
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.
Top comments (1)
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!