Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

oidc-express-middleware

Package Overview
Dependencies
Maintainers
0
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

oidc-express-middleware

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

  • 1.0.17
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
4
decreased by-50%
Maintainers
0
Weekly downloads
 
Created
Source

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.

FAQs

Package last updated on 01 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc