1.0.17 • Published 1 year ago
oidc-express-middleware v1.0.17
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
passportandopenid-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-sessionendpoint
Installation
First, install the required dependencies:
npm install express passport openid-client mongoose connect-redis redis express-sessionUsage
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
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.
Session Management:
- Supports
mongodborredisfor session storage. - Automatically refreshes expired tokens and saves updated tokens back to the session store.
- Supports
Authorization Header:
- Injects the access token as a
Bearertoken in the request headers for authenticated routes.
- Injects the access token as a
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.