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

Published

OIDC Express Middleware is a Node.js library that simplifies the integration of OpenID Connect (OIDC) authentication into your Express applications. It provides seamless handling of login, token retrieval, and session management using a configurable middl

Downloads

314

Readme

OIDC Express Middleware

OIDC Express Middleware is a Node.js library that simplifies the integration of OpenID Connect (OIDC) authentication into your Express applications. It provides seamless handling of login, token retrieval, and session management using a configurable middleware approach, removing the need to manually define routes for login and callback processes.

Features

  • OIDC Client Setup: Automatic OIDC client initialization with discovery URL.
  • Session Management: Stores session information using Redis or MongoDB.
  • Access Token Management: Retrieves and stores access tokens in session automatically.
  • Protected Routes: Middleware ensures authentication for protected routes.
  • Public Routes: Easily define public routes that bypass authentication.
  • Token Refresh: Automatically refreshes expired tokens when possible.

Installation

Install the package via npm:

npm install oidc-express-middleware

Usage

Below is an example of how to set up the middleware in your Express application.

1. Basic Setup

const express = require("express");
const oidcExpressMiddleware = require("oidc-express-middleware");

const app = express();

const options = {
  discoveryUrl: "http://localhost:8080/realms/your-realm", // Keycloak discovery URL
  client_id: "your-client-id", // OIDC client ID
  redirect_uris: ["http://localhost:9000"], // Redirect URI where OIDC will send authorization code
  portalAdminUrl: "http://localhost:9000", // The base URL of your application
  publicRoutes: ["/", "/login", "/logout"], // Routes that do not require authentication
  sessionStorage: {
    type: "redis", // Session storage type: 'redis' or 'mongodb'
    connectionUri: "redis://localhost:6379", // Redis or MongoDB connection URI
    sessionSecret: "your-session-secret", // Secret for session encryption
  },
};

const authMiddlewareLib = oidcExpressMiddleware(options);
app.use(authMiddlewareLib);

const port = 9000;
app.listen(port, () => {
  console.log(`App running at http://localhost:${port}`);
});

2. Middleware Options

discoveryUrl

The URL to discover the OpenID Connect configuration, typically provided by an Identity Provider (IdP) like Keycloak.

client_id

The client ID registered with the Identity Provider (IdP). This is used during the OIDC authentication process.

redirect_uris

An array of allowed redirect URIs for your application. This is where the OIDC server sends authorization codes.

portalAdminUrl

This is the base URL of your application, used to build the OIDC callback URLs.

publicRoutes

An array of routes that are accessible without authentication. These routes bypass the middleware.

sessionStorage

This section configures how user sessions are stored.

  • type: Specifies the session storage backend. Currently supports 'redis' and 'mongodb'.
  • connectionUri: The connection URI for the Redis or MongoDB instance.
  • sessionSecret: The secret used to sign the session ID cookie.

3. Public and Protected Routes

  • Public Routes: Any route specified in the publicRoutes array will bypass authentication checks.
  • Protected Routes: Any route not listed in publicRoutes will be protected by the middleware. If a user tries to access a protected route without being authenticated, they will be automatically redirected to the Identity Provider’s login page.

4. Session Management

  • Session Storage: You can store session data in Redis or MongoDB. Specify the type and connection URI in the sessionStorage option.
  • Token Storage: Access and refresh tokens are stored in the session. The middleware will handle token refreshing if needed.

5. Refresh Token Handling

The middleware will automatically refresh the access token if it expires, provided a refresh token is available. If the refresh fails, the user will be redirected to log in again.

6. Full Example

const express = require("express");
const oidcExpressMiddleware = require("oidc-express-middleware");

const app = express();

const options = {
  discoveryUrl: "http://localhost:8080/realms/myrealm",
  client_id: "myclientid",
  redirect_uris: ["http://localhost:9000"],
  portalAdminUrl: "http://localhost:9000",
  publicRoutes: ["/", "/about", "/login"],
  sessionStorage: {
    type: "redis",
    connectionUri: "redis://localhost:6379",
    sessionSecret: "my-session-secret",
  },
};

const authMiddlewareLib = oidcExpressMiddleware(options);
app.use(authMiddlewareLib);

app.get("/", (req, res) => {
  res.send("Welcome to the public home page!");
});

app.get("/dashboard", (req, res) => {
  // This route is protected; the user must be authenticated
  res.send(`Welcome to the dashboard, ${req.userInfo.name}!`);
});

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

7. Error Handling

You can customize how the library handles authentication and session errors by adding additional middleware or modifying the response logic in your app.

Contributing

Feel free to contribute to this library by submitting pull requests or reporting issues on the GitHub repository.

License

This project is licensed under the MIT License.