Skip to content

Instantly share code, notes, and snippets.

@peter
Last active January 29, 2020 09:36
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 peter/93f04b757b439bd552c93f4dca80be3d to your computer and use it in GitHub Desktop.
Save peter/93f04b757b439bd552c93f4dca80be3d to your computer and use it in GitHub Desktop.
Naive Basic Auth Middleware for Koa
import crypto from 'crypto';
export function basicAuthMiddleware({ name, pass }: any): Function {
const auth = `Basic ${Buffer.from([name, pass].join(':')).toString(
'base64'
)}`;
return async (ctx: any, next: any): Promise<any> => {
const header = ctx.request.get('Authorization');
const headerMatches =
header &&
header.length === auth.length &&
crypto.timingSafeEqual(Buffer.from(header), Buffer.from(auth));
if (headerMatches) {
await next();
} else {
ctx.status = 401;
ctx.set('WWW-Authenticate', 'Basic');
ctx.body = 'Access denied';
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment