Basic Auth 中间件
这个中间件可以为指定路径启用 Basic 认证。 在 Cloudflare Workers 或其他平台上自己实现 Basic 认证往往比想象中复杂,但借助该中间件就能轻松搞定。
想了解 Basic 认证方案在幕后是如何运作的,请查阅 MDN 文档。
Import
ts
import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'用法
ts
const app = new Hono()
app.use(
'/auth/*',
basicAuth({
username: 'hono',
password: 'acoolproject',
})
)
app.get('/auth/page', (c) => {
return c.text('You are authorized')
})若要将认证限定在特定的路由与方法组合:
ts
const app = new Hono()
app.get('/auth/page', (c) => {
return c.text('Viewing page')
})
app.delete(
'/auth/page',
basicAuth({ username: 'hono', password: 'acoolproject' }),
(c) => {
return c.text('Page deleted')
}
)如果你希望自行验证用户,可以指定 verifyUser 选项;返回 true 表示通过认证。
ts
const app = new Hono()
app.use(
basicAuth({
verifyUser: (username, password, c) => {
return (
username === 'dynamic-user' && password === 'hono-password'
)
},
})
)选项
required username:string
进行认证的用户名。
required password:string
与给定用户名匹配的密码。
optional realm:string
作为 WWW-Authenticate 挑战头一部分返回的领域(Realm)名称,默认值为 "Secure Area"。 详情可参阅:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate#directives
optional hashFunction:Function
用于处理哈希并安全比较密码的函数。
optional verifyUser:(username: string, password: string, c: Context) => boolean | Promise<boolean>
自定义的用户验证函数。
optional invalidUserMessage:string | object | MessageFunction
MessageFunction 的签名为 (c: Context) => string | object | Promise<string | object>,用于在用户无效时返回自定义消息。
更多选项
optional ...users:{ username: string, password: string }[]
使用示例
定义多个用户
该中间件也允许传入额外参数,以对象形式定义更多 username 与 password 组合。
ts
app.use(
'/auth/*',
basicAuth(
{
username: 'hono',
password: 'acoolproject',
// Define other params in the first object
realm: 'www.example.com',
},
{
username: 'hono-admin',
password: 'super-secure',
// Cannot redefine other params here
},
{
username: 'hono-user-1',
password: 'a-secret',
// Or here
}
)
)或者减少硬编码:
ts
import { users } from '../config/users'
app.use(
'/auth/*',
basicAuth(
{
realm: 'www.example.com',
...users[0],
},
...users.slice(1)
)
)