Authentication in Node.js can be easily achieved by using various middleware and packages. Here’s an example of how you can do it using Passport.js:
Step 1: Install necessary dependencies with npm
```
npm install —save express passport passport-local express-session cookie-parser body-parser bcrypt-nodejs
```
Step 2: Set up Express and Passport.js in your app
```
var express = require(‘express’);
var passport = require(‘passport’);
var LocalStrategy = require(‘passport-local’).Strategy;
var session = require(‘express-session’);
var bodyParser = require(‘body-parser’);
var cookieParser = require(‘cookie-parser’);
var bcrypt = require(‘bcrypt-nodejs’);
var app = express();
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({ secret: ‘your secret here’, resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
```
Step 3: Configure the local strategy for use by Passport.js
```
passport.use(‘local’, new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
Step 4: Provide serializeUser and deserializeUser functions for passport
```
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
```
Step 5: Define routes that require authentication
```
app.post(‘/login’, passport.authenticate(‘local’, { successRedirect: ‘/’,
failureRedirect: ‘/login’ }));
app.get(‘/logout’, function(req, res) {
req.logout();
res.redirect(‘/’);
});
```
This is a simple example, in real application, we should manage users using a database like MongoDB, MySQL, etc. Don’t forget to secure your form from threats, manage session and encryption, hashing password.