Last active
January 29, 2020 09:36
-
-
Save peter/93f04b757b439bd552c93f4dca80be3d to your computer and use it in GitHub Desktop.
Naive Basic Auth Middleware for Koa
This file contains 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 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