Authentication Basics
-
Authentication verifies user identity and controls access to applications using session-based or token-based authentication methods.
What is Authentication?
Authentication is the process of verifying the identity of a user. It checks whether the user is who they claim to be before granting access to the system.
Why Authentication is Important:
Protects user data
Prevents unauthorized access
Enables personalized user experience
Secures APIs and backend services
Real-World Example
When you log in to a website:
You enter email & password
Server verifies credentials from the database
If valid, access is granted
If invalid, login is rejected
Session vs Token-Based Authentication
Authentication can be implemented in different ways. The two most common approaches are Session-based and Token-based authentication.
Session-Based Authentication
How it Works:
User logs in with credentials
Server creates a session
Session ID is stored on the server
Session ID is sent to client as a cookie
Client sends session ID with every request
Key Characteristics:
Server stores session data
Uses cookies
Easy to implement
Less scalable for large systems
Express Session Setup
Session-Based Authentication in Express.js
This code demonstrates session-based authentication using express-session. The server creates a session when a user logs in, stores the session ID on the server, and sends it to the client as a cookie. Protected routes, like /dashboard, check the session to allow or deny access.
const express = require("express");
const session = require("express-session");
const app = express();
app.use(express.json());
app.use(
session({
secret: "mySecretKey",
resave: false,
saveUninitialized: true
})
);
- Login API (Session Create)
app.post("/login", (req, res) => {
const { username, password } = req.body;
if (username === "admin" && password === "1234") {
req.session.user = username;
res.send("Login successful");
} else {
res.status(401).send("Invalid credentials");
}
});
- Protected Route (Session Check)
app.get("/dashboard", (req, res) => {
if (req.session.user) {
res.send("Welcome to Dashboard");
} else {
res.status(403).send("Login required");
}
});
Flow Summary
Login → Session Created → Session ID stored on server
Request → Session ID cookie → Server verifies session
🔹 Token-Based Authentication
How it Works:
User logs in
Server generates a token (e.g., JWT)
Token is sent to client
Client stores token (localStorage / cookies)
Token is sent in headers for each request
Key Characteristics:
Server does not store user session
Stateless authentication
Highly scalable
Ideal for APIs & mobile apps
Session vs Token Comparison