Open In App

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



Prerequisites

Different Types of Authentication Patterns:

Authentication patterns are used to manage user authentication based on whether or not the server keeps track of or maintains user state or data. There are two types of authentication patterns:



1. Stateless Authentication

The server does not store any data or state of the user between requests. It means each request from the client/ User to the server contains all the data needed to authenticate the user.

Some Stateless authentication strategies in ExpressJS are

A. Basic Authentication




//app.js
 
const express = require("express");
const basicAuth = require("express-basic-auth");
const app = express();
 
app.use(
    basicAuth({
        users: { username: "password" },
        challenge: true,
        unauthorizedResponse:
            "Unauthorized access. Please provide valid credentials.",
    })
);
 
app.get("/secure-data", (req, res) => {
    res.send("This is secure data that requires valid credentials.");
});
 
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

B. Token-Based Authentication:




//app.js
 
const jwt = require("jsonwebtoken");
 
// Generating a token
const token = jwt.sign({ userId: "246" }, "secretKey", { expiresIn: "2h" });
 
// Verifying the token
jwt.verify(token, "secretKey", (err, decoded) => {
    if (err) {
        // Token is invalid
    } else {
        // Token is valid, and decoded contains user information
    }
});

C. OAuth Authentication




//app.js
 
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
 
passport.use(
    new GoogleStrategy(
        {
            clientID: "your-id",
            clientSecret: "your-secret",
            callbackURL: "http://app/callback",
        },
        (accessToken, refreshToken, profile, done) => {
            // Use profile information to create or authenticate a user
            // Call done(null, user) upon success
        }
    )
);
 
app.get(
    "/auth/google",
    passport.authenticate("google", { scope: ["profile", "email"] })
);
 
app.get(
    "/auth/google/callback",
    passport.authenticate("google", {
        successRedirect: "/dashboard",
        failureRedirect: "/login",
    })
);

2. 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




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




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
});

Conclusion

Express provides many strategies for authentication and authorization, each works at specific use cases and requirements. The choice of choosing the authentication strategy for your application depends on the nature of your app, industry standards, and the sensitivity of user data.


Article Tags :