Implementing Local Authentication in NodeJS with PassportJS library.

A Beginner's Guide to Secure User Authentication in NodeJS Applications

Implementing Local Authentication in NodeJS with PassportJS library.

Authentication is an essential part of building secure applications. NodeJS, with its extensive set of libraries and frameworks, makes it easy to implement authentication using different strategies. In this blog, we will explore how to use the local strategy for authentication in NodeJS.

What is Local Strategy?

Local strategy is a simple authentication strategy that involves verifying user credentials against a local database. Simply, the user provides their username and password, and the server checks if those credentials are correct in the database.


Setting Up the Project

Before we start implementing local authentication, let's set up the project. We'll be using the following dependencies:

  • Express: A popular web framework for NodeJS

  • Passport: A middleware for authentication in NodeJS

  • Passport-local: A Passport strategy for local authentication

To install these dependencies, open a terminal in your project directory and run the following command:

npm install express 
npm install passport
npm install passport-local

Once the dependencies are installed, we can create the server file and set up the required middleware.

const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const app = express();

// middleware
app.use(express.urlencoded());
app.use(passport.initialize());
app.use(passport.session());

// routes
app.get('/', (req, res) => {
  res.send('homepage');
});

// start the server
app.listen(8000, () => {
  console.log('Server launched on port 8000');
});

Creating User Model and Database

Next, we need to create a user model and a database to store user information. For this example, we'll be using MongoDB and Mongoose to create the database and user schema.

const mongoose = require('mongoose');

// user schema
const UserSchema = new mongoose.Schema({
  username: String,
  password: String
});

//user model
const User = mongoose.model('User', UserSchema);

// connect to the database

// Connection of NodeJS to localhost
mongoose.connect('mongodb://127.0.0.1:27017/APP_NAME');

//Aquiring connection
const db = mongoose.connection;
console.log('Connecting to DB..');

// On error during connection
db.on('error',console.error.bind(console,"Error connecting to MongoDB :: "));

// Once connection is successful
db.once('open',function(){
    console.log("Connected to Database Successfully::");
})

Implementing Local Strategy

First, we need to define the local strategy using the passport-local library. We do this by creating an instance of the LocalStrategy and passing a verification function as an argument.

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

In conclusion, local authentication is a simple and effective way to secure user authentication in NodeJS applications. With Passport, implementing this authentication strategy becomes even easier. By following the steps outlined in this blog, you can set up local authentication in your NodeJS application quickly and easily.

If you found this blog post helpful, I'd love to connect with you on social media. Happy coding! You can find me on:

- [Twitter](twitter.com/_Shubham_18)

- [LinkedIn](linkedin.com/in/shubham-gulik)

- [GitHub](github.com/Shubhamgulik)

.