npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

oidc-express-middleware

v1.0.17

Published

This library provides an easy-to-use middleware for integrating OpenID Connect (OIDC) authentication into Express applications, supporting session management via MongoDB or Redis.

Downloads

263

Readme

OIDC Express Middleware Library

This library provides an easy-to-use middleware for integrating OpenID Connect (OIDC) authentication into Express applications, supporting session management via MongoDB or Redis.

Features

  • OpenID Connect (OIDC) authentication using passport and openid-client
  • Supports session storage with MongoDB or Redis
  • Token management with automatic refresh handling
  • Authorization header injection for authenticated requests
  • Simple logout with support for Keycloak's end-session endpoint

Installation

First, install the required dependencies:

npm install express passport openid-client mongoose connect-redis redis express-session

Usage

Here’s how to integrate the library into your Express app.

Example

const express = require("express");
const { oidcExpressMiddleware, logout } = require("./middlewares/auth-middleware");

const options = {
  discoveryUrl: "http://localhost:8080/realms/adviseu",
  client_id: "adviseu",
  redirect_uris: ["http://localhost:9000/callback"],
  postLogoutRedirectUri: "http://localhost:9000/public",
  publicRoutes: ["/public"],
  sessionStorage: {
    type: "mongodb",  // Or 'redis' for Redis support
    connectionUri: "mongodb://127.0.0.1:27017/sessions",
    sessionSecret: "secret_key",
    cookie: {
      maxAge: 60000,
    },
  },
};

(async () => {
  const app = express();

  // Initialize OIDC middleware
  const authMiddleware = await oidcExpressMiddleware(options);
  app.use(authMiddleware);

  // Routes
  app.get("/", (req, res) => {
    res.send("OK");
  });

  app.get("/public", (req, res) => {
    res.send("PUBLIC");
  });

  app.get("/login", (req, res) => {
    res.send("LOGIN");
  });

  app.get("/callback", (req, res) => {
    res.redirect("/logged");
  });

  app.get("/logged", (req, res) => {
    console.log(req.headers["Authorization"]);
    res.send("Usuário autenticado com sucesso!");
  });

  // Logout route
  app.get("/logout", async (req, res) => {
    await logout(req, res);
  });

  app.listen(9000, () => {
    console.log("App running on http://localhost:9000");
  });
})();

Key Components

  1. OIDC Middleware:

    • oidcExpressMiddleware(options):
      • discoveryUrl: OIDC Provider discovery URL (e.g., Keycloak's realm URL).
      • client_id: OIDC client ID.
      • redirect_uris: URIs for OIDC callback after authentication.
      • postLogoutRedirectUri: URI for redirection after logout.
      • sessionStorage: Configuration for session storage using either MongoDB or Redis.
  2. Session Management:

    • Supports mongodb or redis for session storage.
    • Automatically refreshes expired tokens and saves updated tokens back to the session store.
  3. Authorization Header:

    • Injects the access token as a Bearer token in the request headers for authenticated routes.
  4. Logout:

    • Supports Keycloak's logout endpoint and session termination with either Redis or MongoDB.

Configuration Options

{
  "discoveryUrl": "URL to OIDC provider's discovery document",
  "client_id": "OIDC client ID",
  "redirect_uris": ["Array of allowed redirect URIs"],
  "postLogoutRedirectUri": "URI to redirect to after logout",
  "publicRoutes": ["Array of public routes that do not require authentication"],
  "sessionStorage": {
    "type": "mongodb or redis",
    "connectionUri": "Database connection URI",
    "sessionSecret": "Secret key for session encryption",
    "cookie": {
      "maxAge": "Session expiration time in milliseconds"
    }
  }
}

Session Storage

MongoDB

To use MongoDB for session storage, provide the following configuration:

{
  "type": "mongodb",
  "connectionUri": "mongodb://127.0.0.1:27017/sessions",
  "sessionSecret": "your_secret",
  "cookie": {
    "maxAge": 60000
  }
}

Redis

To use Redis for session storage, provide the following configuration:

{
  "type": "redis",
  "connectionUri": "redis://127.0.0.1:6379",
  "sessionSecret": "your_secret",
  "cookie": {
    "maxAge": 60000
  }
}

Logout Functionality

The logout function terminates the session and redirects the user to the OIDC provider's logout endpoint:

app.get("/logout", async (req, res) => {
  await logout(req, res);
});

License

MIT License.