Stateful Authentication
In this authentication pattern, the Server stores the state or data of the user about the user session or authentication state. The server uses this information/ Data to authenticate the user. Stateful authentication uses cookies to identify the user with their request. In Express.js Authentication strategies such as Passport.js and Middleware-based authentication can be both stateful or stateless depending on the use case and implementation chosen by developers.
A. Passport.js Middleware
- Passport.js is the authentication middleware for Node.js applications, especially for frameworks like ExpressJS.
- It supports various strategies such as local authentication, OAuth, OpenID, and others.
- It’s flexible to allow developers to choose the strategies that align with their web app the best.
- Passport.JS delegates the intricacies of different strategies to specialized modules.
- This modular design makes it easy to integrate for changing requirements.
Javascript
const passport = require( 'passport' ); const LocalStrategy = require( 'passport-local' ).Strategy; passport.use( new LocalStrategy( (username, password, done) => { // Validate user credentials // If valid, call done(null, user) // Otherwise, call done(null, false, { message: 'Incorrect credentials.' }) } )); app.post( '/login' , passport.authenticate( 'local' , { successRedirect: '/dashboard' , failureRedirect: '/login' , failureFlash: true })); |
B. Middleware-Based Authentication
- Middleware-based authentications involve using custom middleware functions for authorization
- Middleware functions are the functions that have access to the request, response, and the next function in the application’s request-response cycle
- They can modify request and response objects, call the next function, and end the request-response cycle in the stack.
- Middleware-based authentication offers maximum flexibility among others. It allows developers to customize authentication logic to specific application requirements.
Javascript
function authenticate(req, res, next) { // Custom authentication logic if (req.headers.authorization === 'valid-token' ) { return next(); // User is authenticated } else { return res.status(401).json({ message: 'Unauthorized access.' }); } } app.get( '/protected-route' , authenticate, (req, res) => { // Route handling logic for authenticated users }); |
Authentication strategies available in Express
Authentication is an important aspect of web development, which ensures that users accessing an application are who they claim to be. In Express, several authentication strategies are available that help you secure your applications by verifying user identities.
In this article, we will cover the following authentication strategies available in Express
Table of Content
- Stateless Authentication
- Stateful Authentication