,

User Authentication Using JWT with Express.js, Node.js, and MongoDB

Posted by





JWT User Authentication with Express.js, Node.js and MongoDB

JWT User Authentication with Express.js, Node.js and MongoDB

In this article, we will discuss how to implement JWT (JSON Web Token) user authentication in a web application using Express.js, Node.js, and MongoDB. JWT is a standard for securely transmitting information between parties as a JSON object and is commonly used for authentication and information exchange in web applications.

Setting up the Environment

Before we begin implementing JWT user authentication, make sure you have Node.js and MongoDB installed on your machine. You can check the official websites for installation instructions.

Creating a Node.js Application

First, create a new directory for your project and navigate to it in the terminal. Then, run the following command to initialize a new Node.js application:

npm init -y

Next, install the necessary dependencies for our application using the following commands:

npm install express mongoose jsonwebtoken bcrypt

Setting up the Express Server

Create a new file called server.js and add the following code to set up the Express server:

        
const express = require('express');
const app = express();
const mongoose = require('mongoose');

// connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true });

// define routes
app.use('/api/auth', require('./routes/auth'));

// start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log('Server is running on port ' + PORT);
});
        
    

Creating User Authentication Routes

Create a new directory called routes and add a new file called auth.js. In this file, define the routes for user authentication using JWT:

        
const express = require('express');
const router = express.Router();
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

// register a new user
router.post('/register', async (req, res) => {
  try {
    // hash the password
    const hashedPassword = await bcrypt.hash(req.body.password, 10);

    // create a new user
    const user = new User({
      username: req.body.username,
      password: hashedPassword
    });

    // save the user to the database
    await user.save();

    res.status(201).send('User registered successfully');
  } catch (error) {
    res.status(500).send('Error registering user');
  }
});

// login a user
router.post('/login', async (req, res) => {
  const user = await User.findOne({ username: req.body.username });

  if (!user) {
    return res.status(400).send('User not found');
  }

  const validPassword = await bcrypt.compare(req.body.password, user.password);

  if (!validPassword) {
    return res.status(400).send('Invalid password');
  }

  // create a JWT token
  const token = jwt.sign({ _id: user._id }, 'secretkey');

  res.header('auth-token', token).send(token);
});

module.exports = router;
        
    

Securing Routes with JWT

To secure certain routes in your application, you can use a middleware function to verify the JWT token. Here’s an example of how to do this:

        
const jwt = require('jsonwebtoken');

// verify JWT token
function verifyToken(req, res, next) {
  const token = req.header('auth-token');
  
  if (!token) {
    return res.status(401).send('Access denied');
  }

  try {
    const verified = jwt.verify(token, 'secretkey');
    req.user = verified;
    next();
  } catch (error) {
    res.status(400).send('Invalid token');
  }
}

module.exports = verifyToken;
        
    

Conclusion

Implementing JWT user authentication with Express.js, Node.js, and MongoDB provides a secure and convenient way to manage user authentication in a web application. By following the steps outlined in this article, you can create a reliable authentication system for your application.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Eddie4k
7 months ago

MongoDB URL: mongodb+srv://<username>:<password>@<HostName.mongodb.net>/<CollectionName>?retryWrites=true&w=majority
Source Code: https://github.com/Eddie4k-code/SimpleJWTAuth