Creating and Securing JWT Authentication in a Web App

Kosa Matyas - Nov 8 - - Dev Community

Introduction

JSON Web Tokens (JWT) are a compact and self-contained way of securely transmitting information between parties as a JSON object. JWTs are widely used for authenticating users in web applications. In this tutorial, we’ll build a Node.js and Express backend with JWT authentication.

What is JWT?

JWT (JSON Web Token) is an open standard for securely transmitting information between parties as a JSON object. Each token consists of three parts:

  1. Header: Contains information about the token's type and hashing algorithm.
  2. Payload: Contains user information and claims.
  3. Signature: Verifies the integrity of the token.

Example JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0IiwidXNlcm5hbWUiOiJqb2huZG9lIn0.H6BBiB1y5eXKXvW9bbjT2Rg8Jp4oE4Y5Kxf_sDF7Kzg
Enter fullscreen mode Exit fullscreen mode

Setting Up the Project

  1. Create a new project directory:

    mkdir jwt-auth-app
    cd jwt-auth-app
    
  2. Initialize a new Node.js project:

    npm init -y
    

Installing Dependencies

Install the necessary dependencies:

npm install express jsonwebtoken bcryptjs dotenv express-validator
Enter fullscreen mode Exit fullscreen mode
  • express: Web framework for Node.js.
  • jsonwebtoken: Library for generating and verifying JWTs.
  • bcryptjs: Library for hashing passwords.
  • dotenv: For environment variables.
  • express-validator: For validating input data.

Configuring the Server

Create a basic server setup in server.js:

// server.js
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json());

// Import Routes
const authRoutes = require('./routes/auth');
app.use('/api/auth', authRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

Create a .env file for storing environment variables:

PORT=5000
JWT_SECRET=your_jwt_secret_key
Enter fullscreen mode Exit fullscreen mode

Creating User Authentication Routes

  1. Create the routes/auth.js file for authentication routes:
// routes/auth.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const router = express.Router();

const users = []; // In-memory user storage

// Signup Route
router.post(
  '/signup',
  [
    body('username').isLength({ min: 3 }),
    body('password').isLength({ min: 5 })
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });

    const { username, password } = req.body;
    const hashedPassword = await bcrypt.hash(password, 10);

    users.push({ username, password: hashedPassword });
    res.status(201).json({ message: 'User registered successfully' });
  }
);

// Login Route
router.post(
  '/login',
  [
    body('username').notEmpty(),
    body('password').notEmpty()
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });

    const { username, password } = req.body;
    const user = users.find(u => u.username === username);

    if (!user) return res.status(400).json({ message: 'Invalid credentials' });

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });

    const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });
    res.json({ token });
  }
);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode
  1. Explanation of Routes
  • Signup Route: Validates and hashes the password before storing the user.
  • Login Route: Validates credentials, checks password, and issues a JWT token.

Generating JWT Tokens

  • The jwt.sign method generates a token containing the user’s information.
  • The JWT_SECRET is used to sign the token, which should be kept secure and private.
const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });
Enter fullscreen mode Exit fullscreen mode

Securing Routes with JWT

To protect routes, create a middleware to verify tokens.

  1. Create middleware/auth.js:
// middleware/auth.js
const jwt = require('jsonwebtoken');

module.exports = function (req, res, next) {
  const token = req.header('Authorization')?.split(' ')[1];
  if (!token) return res.status(401).json({ message: 'Access denied' });

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (ex) {
    res.status(400).json({ message: 'Invalid token' });
  }
};
Enter fullscreen mode Exit fullscreen mode
  1. Protect Routes in server.js:

Create a protected route that requires a valid token:

// In server.js
const authMiddleware = require('./middleware/auth');

app.get('/api/protected', authMiddleware, (req, res) => {
  res.json({ message: 'This is a protected route', user: req.user });
});
Enter fullscreen mode Exit fullscreen mode

Explanation of Middleware

  • The middleware checks for the presence of the token in the Authorization header.
  • If the token is valid, the user’s information is added to the req object, allowing access to the protected route.

Conclusion

In this tutorial, we’ve covered the basics of setting up JWT authentication in a Node.js and Express backend. This guide demonstrated:

  1. Setting up authentication routes for signup and login.
  2. Creating and verifying JWT tokens.
  3. Securing routes with a JWT-based middleware.

JWTs are a powerful way to handle authentication, making your web applications both secure and scalable.

. . . . .