Skip to content

Instantly share code, notes, and snippets.

@nmattia
Created December 6, 2023 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmattia/c9cf2cbe60663d807840e33f311ec290 to your computer and use it in GitHub Desktop.
Save nmattia/c9cf2cbe60663d807840e33f311ec290 to your computer and use it in GitHub Desktop.
Netlify Edge Function Basic Auth authorization
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