Created
December 6, 2023 10:30
-
-
Save nmattia/c9cf2cbe60663d807840e33f311ec290 to your computer and use it in GitHub Desktop.
Netlify Edge Function Basic Auth authorization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { Config, Context } from "@netlify/edge-functions"; | |
// https://datatracker.ietf.org/doc/html/rfc7617 | |
// base64 encoded "user:pass" | |
const USER_PASS_ENCODED = "dXNlcjpwYXNz"; | |
export default async (request: Request, context: Context) => { | |
const requestAuthentication = () => { | |
const response = new Response(null, { | |
status: 401, | |
headers: { | |
"WWW-Authenticate": 'Basic realm="secret area"', | |
}, | |
}); | |
return response; | |
}; | |
const authHeader = request.headers.get("authorization"); | |
if (authHeader === null) { | |
return requestAuthentication(); | |
} | |
const [basic, userPass] = authHeader.split(" "); | |
if (basic.toLowerCase() !== "basic") { | |
return requestAuthentication(); | |
} | |
// https://datatracker.ietf.org/doc/html/rfc7617 | |
if (userPass !== USER_PASS_ENCODED) { | |
return requestAuthentication(); | |
} | |
return context.next(); | |
}; | |
export const config: Config = { | |
path: "/*", | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment