Support webserver-level HTTP Basic Auth in front of CiviCRM

This commit is contained in:
Joel Brock
2026-05-09 20:49:37 -07:00
parent 234bec5766
commit 82d7849a30
2 changed files with 96 additions and 22 deletions

View File

@@ -6,14 +6,19 @@
* can be developed without a live CiviCRM instance.
*
* Env vars:
* CIVI_BASE_URL e.g. https://crm.fci.coop
* CIVI_API_KEY per-user API key (Civi user "API Key" property)
* CIVI_SITE_KEY site-wide key (from civicrm.settings.php)
* CIVI_BASE_URL e.g. https://crm.fci.coop
* CIVI_API_KEY per-user API key (Civi user "API Key" property)
* CIVI_SITE_KEY site-wide key (from civicrm.settings.php)
* CIVI_HTTP_AUTH_USER (optional) HTTP Basic Auth username, if the site
* itself sits behind webserver-level basic auth
* (common on staging/dev). When set together with
* CIVI_HTTP_AUTH_PASS, every request adds an
* `Authorization: Basic <base64>` header.
* CIVI_HTTP_AUTH_PASS (optional) HTTP Basic Auth password.
*
* If you are seeing STUB MODE warnings, set those three. Auth strategy may
* also need adjustment depending on your CiviCRM auth extension (AuthX vs
* stock APIv3-style site_key/api_key). The header style here matches the
* stock CiviCRM 5+ pattern; AuthX users may need Bearer tokens instead.
* Auth strategy may need adjustment depending on your CiviCRM auth extension
* (AuthX vs stock APIv3-style site_key/api_key). The header style here
* matches the AuthX pattern; classic API3 users may need different headers.
*/
export interface CiviApiOptions {
@@ -56,13 +61,21 @@ export async function civi<T = unknown>(
const body = new URLSearchParams({
params: JSON.stringify(params),
});
const headers: Record<string, string> = {
"Content-Type": "application/x-www-form-urlencoded",
"X-Civi-Auth": `Bearer ${process.env.CIVI_API_KEY}`,
"X-Civi-Key": process.env.CIVI_SITE_KEY!,
};
// Webserver-level HTTP Basic Auth (e.g. site is gated by .htaccess on staging).
if (process.env.CIVI_HTTP_AUTH_USER && process.env.CIVI_HTTP_AUTH_PASS) {
const creds = Buffer.from(
`${process.env.CIVI_HTTP_AUTH_USER}:${process.env.CIVI_HTTP_AUTH_PASS}`,
).toString("base64");
headers["Authorization"] = `Basic ${creds}`;
}
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Civi-Auth": `Bearer ${process.env.CIVI_API_KEY}`,
"X-Civi-Key": process.env.CIVI_SITE_KEY!,
},
headers,
body,
cache: "no-store",
});