DEV Community

Cover image for Implementing Authentication in Node.js
Tannu Goyal
Tannu Goyal

Posted on • Updated on

Implementing Authentication in Node.js

Authentication is a crucial aspect of web applications, especially when building a blog where users need to create accounts, log in, and manage their content securely. In this tutorial, we'll walk you through implementing authentication in a Node.js blog using the popular authentication library, Passport.js, along with a MongoDB database for storing user information.

Prerequisites

Before we begin, make sure you have the following prerequisites installed:

  1. Node.js: You can download and install Node.js from nodejs.org.

  2. MongoDB: Install MongoDB from mongodb.com.

  3. A code editor of your choice (e.g., Visual Studio Code).

Setting Up the Project

  1. Initialize Your Project: Create a new directory for your project and run the following command to initialize a Node.js project with npm:

    npm init -y
    
  2. Install Dependencies: Install the necessary packages:

    npm install express passport passport-local express-session mongoose bcrypt
    
  3. Create Project Structure:
    Create the following project structure:

    ├── app.js
    ├── models
    │   └── User.js
    ├── routes
    │   ├── auth.js
    │   └── index.js
    ├── views
    │   ├── login.ejs
    │   ├── register.ejs
    │   ├── dashboard.ejs
    │   └── home.ejs
    ├── public
    │   └── styles.css
    └── .env
    
  4. Initialize MongoDB Connection:
    In app.js, set up your MongoDB connection using Mongoose:

    const mongoose = require('mongoose');
    
    mongoose.connect('mongodb://localhost/nodejs-blog-auth', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    

    Replace 'mongodb://localhost/nodejs-blog-auth' with your MongoDB connection string.

Implementing Passport.js for Authentication

  1. Configure Passport.js: In app.js, configure Passport.js for authentication:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());
Enter fullscreen mode Exit fullscreen mode
  1. Create User Model: Define a User model in models/User.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: String,
  password: String,
});

module.exports = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode
  1. Implement Passport Local Strategy: Create a Passport Local Strategy for user authentication in config/passport.js:
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/User');

module.exports = function (passport) {
  passport.use(
    new LocalStrategy((username, password, done) => {
      User.findOne({ username: username }, (err, user) => {
        if (err) return done(err);
        if (!user) return done(null, false, { message: 'Incorrect username' });
        if (user.password !== password)
          return done(null, false, { message: 'Incorrect password' });

        return done(null, user);
      });
    })
  );

  passport.serializeUser((user, done) => {
    done(null, user.id);
  });

  passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
      done(err, user);
    });
  });
};
Enter fullscreen mode Exit fullscreen mode
  1. Create Authentication Routes: Create authentication routes for login and registration in routes/auth.js:
const express = require('express');
const router = express.Router();
const passport = require('passport');
const User = require('../models/User');

// Register
router.post('/register', (req, res) => {
  // Implement user registration logic here
});

// Login
router.post(
  '/login',
  passport.authenticate('local', {
    successRedirect: '/dashboard',
    failureRedirect: '/login',
    failureFlash: true,
  })
);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode
  1. Create Views for Authentication: Create login and registration forms in the views directory (login.ejs and register.ejs).

Set Up Routes:
In routes/index.js, set up your main application routes, including the authentication routes:

const express = require('express');
const router = express.Router();

// Define your routes here

module.exports = router;
Enter fullscreen mode Exit fullscreen mode
  1. Include Passport Configuration: Include the Passport configuration in app.js:
require('./config/passport')(passport);
Enter fullscreen mode Exit fullscreen mode
  1. Start the Server: Start your Express server in app.js:
const PORT = process.env.PORT || 3000;

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

Conclusion
In this tutorial, we've laid out the foundation for implementing authentication in a Node.js blog using Passport.js and MongoDB. You can now expand upon this foundation to add user registration, password reset, and user profile functionality. Remember to handle security best practices, such as hashing passwords securely and implementing user input validation.

Feel free to explore more features like user roles, JWT authentication, and authorization to enhance the security and functionality of your Node.js blog.

Top comments (1)

Collapse
 
keshavsardana profile image
Keshav

Informative