本系列是我的常用 koa 中间件使用笔记,防止忘记使用方法而作记录
basic-auth 会帮我们解析 http header 的 authorization 内的值,这个值通常是使用 base64 加密的。
使用方法
const Koa = require('koa');
const app = new Koa();
const auth = require('basic-auth')
app.use(async (ctx, next) => {
let a = auth(ctx.request);
console.log(a); //解析的值
})
app.listen(3000);
在 postman 中这样提交就可以被解析到

手动解析 authorization
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
let auth = ctx.request.header.authorization; //http header的值
auth = auth.split(' ')[1]; //有"basic "的前缀,用split分割空格取值
auth = Buffer.from(auth, 'base64').toString().split(':')[0]; //解析base64,转化为字符串,而且他有一个“:”的符号,需要分割
console.log(auth); //结果
})
app.listen(3000);
这篇博客介绍了如何在Koa应用中使用`basic-auth`中间件来解析HTTP请求头中的Authorization字段,该字段通常包含Base64加密的认证信息。通过示例代码展示了如何手动和使用中间件解析Base64编码的授权信息,并提供了在Postman中模拟测试的方法。
1154





