basic-auth-for-vercel-middleware
Version:
Basic Authentication for vercel middleware
26 lines (25 loc) • 964 B
JavaScript
import { next } from "@vercel/edge";
const unauthorized = (body) => {
return new Response(body, {
status: 401,
statusText: "'Authentication required.'",
headers: {
"WWW-Authenticate": 'Basic realm="User Visible Realm"',
},
});
};
const createBasicAuthHandler = (authInfo, unauthorizedText = "Authentication required.", skip = false) => {
return (request) => {
if (skip === true || (typeof skip === "function" && skip(request)))
return next();
const authorization = request.headers.get("Authorization");
if (authorization) {
const [_, basicAuth] = authorization.split(" ");
const [user, password] = atob(basicAuth).toString().split(":");
if (user === authInfo.name && password === authInfo.password)
return next();
}
return unauthorized(unauthorizedText);
};
};
export default createBasicAuthHandler;