Handling authentication and authorization in Node.js is all about verifying who the user is (authentication) and controlling what they can access (authorization).
Authentication (Who are you?)
Authentication is usually implemented using JWT (JSON Web Tokens) or sessions.
Common Flow (JWT-based)
- User logs in with email/password
- Server verifies credentials
- Server generates a JWT token
- Client stores token (localStorage / cookies)
- Token is sent with every request
Example (JWT Authentication)
const jwt = require("jsonwebtoken");
// Generate Token (on login)
const token = jwt.sign(
{ userId: user._id },
"secretKey",
{ expiresIn: "1h" }
);
Middleware to Verify Token
const verifyToken = (req, res, next) => {
const token = req.headers.authorization;
if (!token) return res.status(401).send("Access denied");
try {
const verified = jwt.verify(token, "secretKey");
req.user = verified;
next();
} catch (err) {
res.status(400).send("Invalid token");
}
};
Authorization (What can you do?)
After authentication, we check permissions or roles.
Role-Based Authorization Example
const authorizeRole = (role) => {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).send("Forbidden");
}
next();
};
};
Using Both Together
app.get("/admin", verifyToken, authorizeRole("admin"), (req, res) => {
res.send("Welcome Admin");
});
Other Authentication Methods
1. Session-Based Authentication
- Uses cookies + server-side sessions
- Stored in memory/Redis
- Common with traditional apps
2. OAuth (Social Login)
- Login via Google, Facebook, GitHub
- Implemented using libraries like Passport.js
3. API Keys (for services)
- Used in backend-to-backend communication
Best Practices
- Always hash passwords using bcrypt
- Use HTTPS to secure data
- Store tokens securely (prefer httpOnly cookies)
- Keep JWT expiry short and use refresh tokens
- Validate user input to prevent attacks
- Implement rate limiting to prevent brute force
Real-world Example
In production apps:
- Login → JWT issued
- Middleware → verifies token on every request
- Role check → restricts routes (admin/user)
- Sensitive routes → extra validation
Key Takeaway
Authentication ensures user identity, while authorization ensures access control. In Node.js, this is typically implemented using JWT + middleware + role-based checks, making the system secure and scalable for modern applications.