Authorization and Authentication in Node.js: A Complete Guide
In modern web development, user data security is the number one priority. In this guide, we will break down the key tools and libraries for implementing authentication (verifying user identity) and authorization (checking access rights) in Node.js applications. You will learn how to set up route protection, hash passwords, and work with access tokens.
1. Basic Concepts
- Authentication — the process of verifying whether a user is who they claim to be (usually via login and password).
- Authorization — determining which resources and actions are available to an authenticated user.
- JWT (JSON Web Token) — a compact and self-contained way to transmit data as a JSON object. Used for creating access tokens.
- Sessions — a traditional method of storing user data on the server (usually using
express-session).
2. Key Libraries for Node.js
2.1. bcrypt — Password Hashing
Never store passwords in plain text. bcrypt is a library for secure hashing using salt.
const bcrypt = require('bcrypt');const saltRounds = 10;
// Hashing a passwordasync function hashPassword(password) { const salt = await bcrypt.genSalt(saltRounds); const hash = await bcrypt.hash(password, salt); return hash;}
// Verifying a passwordasync function checkPassword(password, hash) { const match = await bcrypt.compare(password, hash); return match; // true or false}2.2. jsonwebtoken — Working with JWT
The jsonwebtoken library allows you to create and verify JWT tokens. Tokens typically consist of a header, payload, and signature.
const jwt = require('jsonwebtoken');const secretKey = 'your-secret-key';
// Creating a tokenfunction generateToken(userId, role) { const payload = { userId, role }; const token = jwt.sign(payload, secretKey, { expiresIn: '1h' }); return token;}
// Verifying a token (middleware)function verifyToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN if (!token) return res.status(401).json({ error: 'Token not provided' });
jwt.verify(token, secretKey, (err, decoded) => { if (err) return res.status(403).json({ error: 'Invalid token' }); req.user = decoded; next(); });}2.3. Passport.js — Universal Authentication
Passport.js is an Express middleware supporting over 500 strategies (local, OAuth, JWT, Google, Facebook, etc.). Example of a local strategy:
const passport = require('passport');const LocalStrategy = require('passport-local').Strategy;const User = require('./models/User');
passport.use(new LocalStrategy( async (username, password, done) => { try { const user = await User.findOne({ username }); if (!user) return done(null, false, { message: 'User not found' }); const isValid = await bcrypt.compare(password, user.password); if (!isValid) return done(null, false, { message: 'Incorrect password' }); return done(null, user); } catch (err) { return done(err); } }));
// Serialization and deserialization (for sessions)passport.serializeUser((user, done) => done(null, user.id));passport.deserializeUser(async (id, done) => { const user = await User.findById(id); done(null, user);});3. Full Example: Registration and Login
Let's put it all together in a simple Express application.
const express = Also in library
Working with S3 and Cloud Storage in Swift (iOS/macOS): AWSS3 Library
Event Bus and Observer Pattern in Go (Golang): Implementation and Examples
Caching in TypeScript: Redis, Memcached, and In-Memory Solutions
InversifyJS: IoC Container for TypeScript Applications