From f213ca52a61612ea9c7c823330fd4ecb21200d1e Mon Sep 17 00:00:00 2001 From: carlgu Date: Fri, 25 Oct 2024 10:14:11 +0200 Subject: [PATCH] Add http basic auth integration for a list of credentials --- CHANGELOG.md | 6 ++++++ src/next/middleware/http-auth.ts | 35 ++++++++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58662ad..4870c26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +2.3.1 +===== + +* (improvement) Add method `integrateHttpBasicAuth()` for handling a list of Http Basic Auth Credentials +* (deprecation) Deprecate `handleHttpBasicAuth` method + 2.3.0 ===== diff --git a/src/next/middleware/http-auth.ts b/src/next/middleware/http-auth.ts index e050f21..53426ca 100644 --- a/src/next/middleware/http-auth.ts +++ b/src/next/middleware/http-auth.ts @@ -1,7 +1,14 @@ import type {NextRequest} from "next/server"; +export interface Credentials { + username: string; + password: string; +} + /** * Handles basic authentication + * + * @deprecated Use the new method 'integrateHttpBasicAuth' allowing a list of credentials to check against instead */ export function handleHttpBasicAuth ( request: NextRequest, @@ -10,6 +17,24 @@ export function handleHttpBasicAuth ( responseText: string = "Auth required", realmLabel: string = "Secure Area", ) : Response | undefined +{ + return integrateHttpBasicAuth( + request, + [{username: username, password: password}], + responseText, + realmLabel + ); +} + +/** + * Handles basic authentication + */ +export function integrateHttpBasicAuth ( + request: NextRequest, + users: Credentials[], + responseText: string = "Auth required", + realmLabel: string = "Secure Area", +) : Response | undefined { const auth = request.headers.get("authorization"); const authToken = /^Basic (?.*?)$/.exec(auth || ""); @@ -20,10 +45,12 @@ export function handleHttpBasicAuth ( .toString() .split(":"); - if (givenUser === username && givenPassword === password) - { - return; - } + users.forEach((item) => { + if (givenUser === item.username && givenPassword === item.password) + { + return; + } + }) } return new Response(responseText, {