Authentication and Authorization in Express

📘 Express.js 👁 52 views 📅 Nov 05, 2025
⏱ Estimated reading time: 3 min

In web applications, Authentication and Authorization are critical for security:

  • Authentication – Verifies the identity of a user (login/signup).

  • Authorization – Determines what a user can access based on their role or permissions.

Express.js does not include built-in authentication, but you can implement it using middleware, JWT, Passport.js, or session-based methods.


1. Authentication Methods

a) Session-Based Authentication

  • Uses express-session to store user login sessions on the server.

Setup:

npm install express express-session bcrypt

Example:

const express = require('express'); const session = require('express-session'); const bcrypt = require('bcrypt'); const app = express(); app.use(express.json()); app.use(session({ secret: 'mysecretkey', resave: false, saveUninitialized: true })); // Dummy user const user = { id: 1, username: 'admin', password: '$2b$10$...' }; // hashed password // Login route app.post('/login', async (req, res) => { const { username, password } = req.body; if (username === user.username && await bcrypt.compare(password, user.password)) { req.session.userId = user.id; return res.send('Logged in'); } res.status(401).send('Invalid credentials'); }); // Protected route app.get('/dashboard', (req, res) => { if (!req.session.userId) return res.status(401).send('Unauthorized'); res.send('Welcome to dashboard'); });

b) Token-Based Authentication (JWT)

  • Uses JSON Web Tokens (JWT) to authenticate users.

  • Tokens are sent with each request instead of storing sessions on the server.

Setup:

npm install jsonwebtoken bcrypt

Example:

const jwt = require('jsonwebtoken'); const secretKey = 'mysecretkey'; // Login route app.post('/login', async (req, res) => { const { username, password } = req.body; if (username === 'admin' && password === '1234') { const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' }); return res.json({ token }); } res.status(401).send('Invalid credentials'); }); // Middleware to protect routes function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) return res.status(401).send('Access denied'); jwt.verify(token, secretKey, (err, user) => { if (err) return res.status(403).send('Invalid token'); req.user = user; next(); }); } // Protected route app.get('/dashboard', authenticateToken, (req, res) => { res.send(`Hello ${req.user.username}, welcome to dashboard`); });

2. Authorization

  • Authorization determines what a logged-in user can do.

  • Often done by checking roles or permissions.

Example:

function authorizeRole(role) { return (req, res, next) => { if (req.user.role !== role) return res.status(403).send('Forbidden'); next(); }; } // Admin-only route app.get('/admin', authenticateToken, authorizeRole('admin'), (req, res) => { res.send('Welcome Admin'); });
  • authenticateToken ensures the user is logged in

  • authorizeRole ensures the user has proper permissions


3. Best Practices

  1. Never store plain passwords – always hash with bcrypt.

  2. Use HTTPS to protect tokens and session cookies.

  3. Keep JWT secrets secure and rotate periodically.

  4. Implement role-based access control (RBAC) for authorization.

  5. Use middleware to centralize authentication and authorization logic.

  6. Set token expiration times and handle token refresh securely.


4. Popular Libraries for Authentication in Express

LibraryUse Case
Passport.jsSupports many strategies (JWT, OAuth, local)
jsonwebtokenJWT-based token authentication
bcryptPassword hashing
express-sessionSession-based authentication

5. Summary Flow

  1. User logs in → Credentials checked → Issue session or JWT.

  2. Client sends request → Include token/session.

  3. Server middleware verifies → Grant or deny access.

  4. Authorization checks → Confirm user has permission.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes