Skip to content

Introduction to JWT Authentication

In this guide, we’ll learn how to set up a simple authentication system using JWT (JSON Web Token) in a Node.js application. JWT is widely used for securely transmitting information between clients and servers.

  1. Hashing and Comparing Passwords:

    • We use bcrypt to hash user passwords and securely compare them during login.
  2. User Login:

    • We handle user login by creating a POST route where users submit their email and password.
  3. Session Management with JWT:

    • Instead of traditional session cookies, we use JWT to manage authentication. A token is generated upon successful login and sent to the user to include in future requests for authentication.
  4. Route Protection with JWT:

    • We protect routes (e.g., /dashboard) by verifying the JWT in the request headers to ensure only authenticated users can access the page.
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
// Example login route using JWT
http
.createServer((req, res) => {
if (method === "POST" && parsedUrl.pathname === "/login") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
const { email, password } = JSON.parse(body); // Parse the JSON body
const user = users[email];
if (user && bcrypt.compareSync(password, user.password)) {
// Generate JWT on successful login
const token = jwt.sign({ email: user.email }, "your_secret_key", {
expiresIn: "1h",
});
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Login successful!", token }));
} else {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Invalid email or password" }));
}
});
return;
}
if (method === "GET" && parsedUrl.pathname === "/dashboard") {
const authHeader = req.headers["authorization"];
if (authHeader) {
const token = authHeader.split(" ")[1]; // Extract JWT from Authorization header
jwt.verify(token, "your_secret_key", (err, decoded) => {
if (err) {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Unauthorized access" }));
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Welcome to your dashboard!</h1>");
}
});
} else {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Authorization token required" }));
}
}
})
.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});