Skip to content

基本身份验证中间件

🌐 Basic Auth Middleware

这个中间件可以对指定路径应用基本身份验证。在 Cloudflare Workers 或其他平台上实现基本身份验证比看起来更复杂,但使用这个中间件就轻而易举了。

🌐 This middleware can apply Basic authentication to a specified path. Implementing Basic authentication with Cloudflare Workers or other platforms is more complicated than it seems, but with this middleware, it's a breeze.

有关 Basic 身份验证方案底层工作原理的更多信息,请参阅 MDN 文档

🌐 For more information about how the Basic auth scheme works under the hood, see the MDN docs.

导入

🌐 Import

ts
import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'

用法

🌐 Usage

ts
const app = new Hono()

app.use(
  '/auth/*',
  basicAuth({
    username: 'hono',
    password: 'acoolproject',
  })
)

app.get('/auth/page', (c) => {
  return c.text('You are authorized')
})

要限制到特定路由 + 方法:

🌐 To restrict to a specific route + method:

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 表示已被接受。

🌐 If you want to verify the user by yourself, specify the verifyUser option; returning true means it is accepted.

ts
const app = new Hono()

app.use(
  basicAuth({
    verifyUser: (username, password, c) => {
      return (
        username === 'dynamic-user' && password === 'hono-password'
      )
    },
  })
)

选项

🌐 Options

required 用户名: string

正在进行身份验证的用户的用户名。

🌐 The username of the user who is authenticating.

required 密码:string

提供的用户名的密码值,用于进行身份验证。

🌐 The password value for the provided username to authenticate against.

optional 字段:string

作为返回的 WWW-Authenticate 挑战头部的一部分,字段的域名。默认值是 "Secure Area"
查看更多: https://web.nodejs.cn/zh-CN/docs/Web/HTTP/Headers/WWW-Authenticate#directives

🌐 The domain name of the realm, as part of the returned WWW-Authenticate challenge header. The default is "Secure Area".
See more: https://web.nodejs.cn/en-US/docs/Web/HTTP/Headers/WWW-Authenticate#directives

optional 哈希函数: Function

用于处理哈希函数以安全地比较密码的函数。

🌐 A function to handle hashing for safe comparison of passwords.

optional 验证用户: (username: string, password: string, c: Context) => boolean | Promise<boolean>

验证用户的函数。

🌐 The function to verify the user.

optional 无效的用户消息: string | object | MessageFunction

MessageFunction(c: Context) => string | object | Promise<string | object>。如果用户无效,将显示自定义消息。

optional onAuthSuccess: (c: Context, username: string) => void | Promise<void>

在成功认证后调用的回调函数。这允许你设置上下文变量或执行副作用,而无需重新解析授权头。

🌐 A callback function invoked after successful authentication. This allows you to set context variables or perform side effects without re-parsing the Authorization header.

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}!`)
})

更多选项

🌐 More Options

optional ...用户:{ username: string, password: string }[]

秘诀

🌐 Recipes

定义多个用户

🌐 Defining Multiple Users

这个中间件还允许你传递包含定义更多 usernamepassword 对象的任意参数。

🌐 This middleware also allows you to pass arbitrary parameters containing objects defining more username and password pairs.

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

或更少的硬编码:

🌐 Or less hardcoded:

ts
import { users } from '../config/users'

app.use(
  '/auth/*',
  basicAuth(
    {
      realm: 'www.example.com',
      ...users[0],
    },
    ...users.slice(1)
  )
)

Hono 中文网 - 粤ICP备13048890号