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.