You are currently viewing Authentication with Node.js and JSON Web Tokens (JWT)

Authentication with Node.js and JSON Web Tokens (JWT)

  • Post author:
  • Post category:Nodejs
  • Post comments:0 Comments
  • Post last modified:May 3, 2024

In this tutorial, we’ll explore how to implement authentication in a Node.js application using JSON Web Tokens (JWT). JSON Web Tokens are a compact, URL-safe means of representing claims to be transferred between two parties. We’ll cover the basics of JWT, how to generate and verify tokens, and integrate them into a simple Node.js application for authentication purposes.

Prerequisites

Before starting this tutorial, you should have the following installed:

  • Node.js and npm installed on your machine.

Step 1: Setting Up a Node.js Project

First, let’s set up a new Node.js project. Create a new directory for your project and navigate into it:

mkdir nodejs-jwt-tutorial
cd nodejs-jwt-tutorial

Initialize a new Node.js project by running:

npm init -y

This will create a package.json file with default values.

Step 2: Installing Dependencies

We’ll need a few dependencies for this project. Install express for creating our server, and jsonwebtoken for working with JWT:

npm install express jsonwebtoken

Step 3: Creating a Basic Express Server

Create a new file named server.js and set up a basic Express server:

// server.js

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Welcome to Node.js JWT Tutorial!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Step 4: Generating JWT Tokens

Now let’s implement a simple authentication mechanism using JWT. We’ll create a /login endpoint where users can authenticate and receive a JWT token upon successful login.

// server.js

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
const port = 3000;

// Mock user data
const users = [
  { id: 1, username: 'user1', password: 'password1' },
  { id: 2, username: 'user2', password: 'password2' },
];

app.use(express.json());

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);

  if (user) {
    // Generate JWT token
    const token = jwt.sign({ userId: user.id }, 'secret_key');
    res.json({ token });
  } else {
    res.status(401).json({ message: 'Invalid username or password' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Step 5: Verifying JWT Tokens

Now, let’s create an endpoint /protected which requires a valid JWT token for access. We’ll implement a middleware function to verify the JWT token before allowing access to this endpoint.

// server.js

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
const port = 3000;

// Mock user data
const users = [
  { id: 1, username: 'user1', password: 'password1' },
  { id: 2, username: 'user2', password: 'password2' },
];

// Middleware to verify JWT token
const verifyToken = (req, res, next) => {
  const token = req.headers['authorization'];

  if (!token) {
    return res.status(401).json({ message: 'No token provided' });
  }

  jwt.verify(token, 'secret_key', (err, decoded) => {
    if (err) {
      return res.status(403).json({ message: 'Failed to authenticate token' });
    }
    req.userId = decoded.userId;
    next();
  });
};

app.use(express.json());

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);

  if (user) {
    // Generate JWT token
    const token = jwt.sign({ userId: user.id }, 'secret_key');
    res.json({ token });
  } else {
    res.status(401).json({ message: 'Invalid username or password' });
  }
});

app.get('/protected', verifyToken, (req, res) => {
  res.json({ message: 'Protected resource accessed successfully' });
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Step 6: Testing the Endpoints

Now that our server is set up, let’s test our endpoints:

  1. Start the server by running node server.js.
  2. Use tools like Postman or curl to send requests.
  • To authenticate and receive a token:
  POST http://localhost:3000/login
  Content-Type: application/json

  {
    "username": "user1",
    "password": "password1"
  }

You will receive a JWT token in the response.

  • To access the protected endpoint:
  GET http://localhost:3000/protected
  Authorization: Bearer <token>

Replace <token> with the JWT token received during login.

You should receive a response indicating successful access to the protected resource.

This tutorial provides a basic understanding of JWT authentication and how to integrate it into your Node.js projects. Feel free to expand upon this foundation to build more sophisticated authentication systems.

Leave a Reply