Implementing Basic Authentication with JWT

Implementing Basic Authentication with JWT

Last updated: 3/7/2025

1 hour
Medium

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. πŸš€