Dynamically Set baseURL Per Request in express-openid-connect
Last Updated:
Overview
This article clarifies how to dynamically set the baseURL for each request in express-openid-connect. This addresses scenarios where an application is accessed from multiple clients, but the middleware configuration appears to support only a single, static baseURL.
Applies To
-
express-openid-connect
Cause
This functionality can be configured by creating multiple auth instances when the application mounts, one for each required baseURL. A custom middleware can then dynamically select the correct auth instance based on the request.
For example, to support two separate base URLs (e.g., one for internal and one for external access), configure the application as follows:
import { auth } from 'express-openid-connect';
const configParams = {
// ...my config
};
const internalBaseUrl = 'https://mycompany.local';
const externalBaseUrl = 'https://mycompany.com';
const internalAuth = auth({ ...configParams, baseURL: internalBaseUrl });
const externalAuth = auth({ ...configParams, baseURL: externalBaseUrl });
const auth0Mw = (req, res, next) => {
const baseURL = `${req.protocol}://${req.header('x-forwarded-host') || req.get('host')}`;
return (baseURL === internalBaseUrl ? internalAuth : externalAuth)(req, res, next);
};
This approach is also discussed in express-openid-connect GitHub issue 200.
Solution
This setup can occur when the app mounts, for example, if two base URLs are required for the internet and intranet:
import { auth } from 'express-openid-connect';
const configParams = {
// ...my config
};
const internalBaseUrl = 'https://mycompany.local';
const externalBaseUrl = 'https://mycompany.com';
const internalAuth = auth({ ...configParams, baseURL: internalBaseUrl });
const externalAuth = auth({ ...configParams, baseURL: externalBaseUrl });
const auth0Mw = (req, res, next) => {
const baseURL = `${req.protocol}://${req.header('x-forwarded-host') || req.get('host')}`;
return (baseURL === internalBaseUrl ? internalAuth : externalAuth)(req, res, next);
};