Implementing Basic Authentication with JWT
Implementing Basic Authentication with JWT
Last updated: 3/7/2025
Implementing Basic Authentication in a REST API
π Introduction
In the previous lesson, we learned how authentication works in APIs and introduced JWT (JSON Web Tokens).
Now, letβs implement user authentication in an Express.js API by:
β
Setting up user registration (signup)
β
Implementing password hashing for security
β
Creating a login endpoint that returns a JWT
β
Using a database to store users
π 1. Setting Up the Project
β Step 1: Initialize a Node.js Project
Run the following commands:
mkdir auth-api cd auth-api npm init -y
β Step 2: Install Dependencies
npm install express bcryptjs jsonwebtoken dotenv mongoose cors
- express β Backend framework
- bcryptjs β Secure password hashing
- jsonwebtoken β JWT authentication
- dotenv β Manage environment variables
- mongoose β MongoDB database connection
- cors β Allow cross-origin requests
π 2. Setting Up the Express Server
Create a new file server.js
and set up an Express server:
require("dotenv").config(); const express = require("express"); const mongoose = require("mongoose"); const app = express(); app.use(express.json()); // Middleware to parse JSON // Connect to MongoDB mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }); app.listen(3033, () => console.log("Server running on port 3033"));
β
Create a .env
file and add:
MONGO_URI=mongodb://localhost:27017/authdb
JWT_SECRET=mysecretkey
π 3. Creating the User Model
Create a new file models/User.js
and define the User schema:
const mongoose = require("mongoose"); const UserSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, }); module.exports = mongoose.model("User", UserSchema);
π 4. Implementing User Registration (Signup)
Create a new file routes/auth.js
and add the signup route:
const express = require("express"); const bcrypt = require("bcryptjs"); const User = require("../models/User"); const router = express.Router(); // Signup Route router.post("/signup", async (req, res) => { try { const { name, email, password } = req.body; // Check if user already exists let user = await User.findOne({ email }); if (user) return res.status(400).json({ error: "User already exists" }); // Hash the password const hashedPassword = await bcrypt.hash(password, 10); // Save user user = new User({ name, email, password: hashedPassword }); await user.save(); res.status(201).json({ message: "User registered successfully" }); } catch (error) { res.status(500).json({ error: "Server error" }); } }); module.exports = router;
β
Add the route to server.js
const authRoutes = require("./routes/auth"); app.use("/auth", authRoutes);
π 5. Implementing User Login & JWT Generation
Modify routes/auth.js
to add the login route:
const jwt = require("jsonwebtoken"); // Login Route router.post("/login", async (req, res) => { try { const { email, password } = req.body; // Check if user exists const user = await User.findOne({ email }); if (!user) return res.status(400).json({ error: "Invalid credentials" }); // Compare password const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ error: "Invalid credentials" }); // Generate JWT const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" }); res.json({ token }); } catch (error) { res.status(500).json({ error: "Server error" }); } });
β Now users can log in and receive a JWT.
π 6. Testing Authentication
β 1οΈβ£ Register a New User
Send a POST request to /auth/signup
with:
{ "name": "Alice", "email": "alice@example.com", "password": "mypassword" }
π‘ Response:
{ "message": "User registered successfully" }
β 2οΈβ£ Log In and Get a Token
Send a POST request to /auth/login
with:
{ "email": "alice@example.com", "password": "mypassword" }
π‘ Response:
{ "token": "eyJhbGciOiJIUzI1NiIs..." }
π― Summary
- We set up user authentication in an API.
- Passwords are hashed before storing them.
- Users can register and log in.
- After login, users receive a JWT token for authentication.
β Next Lesson: Securing API Routes with Authentication Middleware
Now that users can log in, weβll learn how to protect API routes so only authenticated users can access them. π