跳转到正文

Basic Auth 中间件 ​

此中间件可以为指定路径应用 HTTP 基本身份验证。 在 Cloudflare Workers 或其他平台上实现基本身份验证比想象中复杂,但使用此中间件就很简单。

有关基本身份验证方案的工作原理,请参阅 MDN 文档。

导入 ​

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 质询响应头的一部分。默认值为 "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 onAuthSuccess: (c: Context, username: string) => void | Promise<void> ​

验证成功后调用的回调函数。可用于设置上下文变量或执行副作用,无需再次解析 Authorization 请求头。

ts
app.use(
  '/auth/*',
  basicAuth({
    username: 'hono',
    password: 'acoolproject',
    onAuthSuccess: (c, username) => {
      c.set('username', username)
    },
  })
)

app.get('/auth/page', (c) => {
  const username = c.get('username')
  return c.text(`Hello, ${username}!`)
})

更多选项 ​

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)
  )
)

基于 MIT 许可证发布。