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.

有关基本身份验证方案在后台如何工作的更多信息,请参阅 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

<徽章类型="danger" text="required" /> username:string

¥required username: string

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

¥The username of the user who is authenticating.

required password:string

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

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

<徽章类型="info" 文本="optional" /> 字段:string

¥optional realm: string

字段的域名,作为返回的 WWW-Authenticate 质询标头的一部分。默认为 "Secure Area"。查看更多:https://web.nodejs.cn/en-US/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 hashFunction:Function

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

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

optional verifyUser:(username: string, password: string, c: Context) => boolean | Promise<boolean>

验证用户的函数。

¥The function to verify the user.

optional invalidUserMessage:string | object | MessageFunction

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

¥MessageFunction is (c: Context) => string | object | Promise<string | object>. The custom message if the user is invalid.

更多选项

¥More Options

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

¥optional ...users: { 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 v4.7 中文网 - 粤ICP备13048890号