Skip to content

Bearer Auth 中间件

🌐 Bearer Auth Middleware

Bearer Auth 中间件通过验证请求头中的 API 令牌提供身份验证。访问该端点的 HTTP 客户端将添加 Authorization 头,并将 Bearer {token} 作为头值。

🌐 The Bearer Auth Middleware provides authentication by verifying an API token in the Request header. The HTTP clients accessing the endpoint will add the Authorization header with Bearer {token} as the header value.

在终端使用 curl,看起来会是这样的:

🌐 Using curl from the terminal, it would look like this:

sh
curl -H 'Authorization: Bearer honoiscool' http://localhost:8787/auth/page

导入

🌐 Import

ts
import { Hono } from 'hono'
import { bearerAuth } from 'hono/bearer-auth'

用法

🌐 Usage

NOTE

你的 token 必须匹配正则表达式 /[A-Za-z0-9._~+/-]+=*/,否则将返回 400 错误。值得注意的是,该正则表达式既适用于 URL 安全的 Base64 编码 JWT,也适用于标准 Base64 编码的 JWT。此中间件并不要求承载令牌必须是 JWT,只需它匹配上述正则表达式即可。

ts
const app = new Hono()

const token = 'honoiscool'

app.use('/api/*', bearerAuth({ token }))

app.get('/api/page', (c) => {
  return c.json({ message: 'You are authorized' })
})

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

🌐 To restrict to a specific route + method:

ts
const app = new Hono()

const token = 'honoiscool'

app.get('/api/page', (c) => {
  return c.json({ message: 'Read posts' })
})

app.post('/api/page', bearerAuth({ token }), (c) => {
  return c.json({ message: 'Created post!' }, 201)
})

要实现多个令牌(例如,任何有效令牌都可以读取,但创建/更新/删除仅限于特权令牌):

🌐 To implement multiple tokens (E.g., any valid token can read but create/update/delete are restricted to a privileged token):

ts
const app = new Hono()

const readToken = 'read'
const privilegedToken = 'read+write'
const privilegedMethods = ['POST', 'PUT', 'PATCH', 'DELETE']

app.on('GET', '/api/page/*', async (c, next) => {
  // List of valid tokens
  const bearer = bearerAuth({ token: [readToken, privilegedToken] })
  return bearer(c, next)
})
app.on(privilegedMethods, '/api/page/*', async (c, next) => {
  // Single valid privileged token
  const bearer = bearerAuth({ token: privilegedToken })
  return bearer(c, next)
})

// Define handlers for GET, POST, etc.

如果你想自己验证令牌的值,请指定 verifyToken 选项;返回 true 表示它已被接受。

🌐 If you want to verify the value of the token yourself, specify the verifyToken option; returning true means it is accepted.

ts
const app = new Hono()

app.use(
  '/auth-verify-token/*',
  bearerAuth({
    verifyToken: async (token, c) => {
      return token === 'dynamic-token'
    },
  })
)

选项

🌐 Options

required 令牌: string | string[]

用于验证传入 bearer 令牌的字符串。

🌐 The string to validate the incoming bearer token against.

optional 字段:string

作为返回的 WWW-Authenticate 挑战头的一部分,字段的域名。默认值是 ""。 更多信息请参见: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 "". See more: https://web.nodejs.cn/en-US/docs/Web/HTTP/Headers/WWW-Authenticate#directives

optional 前缀:string

Authorization 头部值的前缀(也称为 schema)。默认值是 "Bearer"

🌐 The prefix (or known as schema) for the Authorization header value. The default is "Bearer".

optional headerName: string

头部名称。默认值为 Authorization

🌐 The header name. The default value is Authorization.

optional 哈希函数: Function

用于处理哈希函数以安全地比较身份验证令牌的函数。

🌐 A function to handle hashing for safe comparison of authentication tokens.

optional 验证令牌: (token: string, c: Context) => boolean | Promise<boolean>

验证令牌的函数。

🌐 The function to verify the token.

optional 无认证头: object

自定义请求缺少身份验证标头时的错误响应。

🌐 Customizes the error response when the request does not have an authentication header.

  • wwwAuthenticateHeaderstring | object | MessageFunction - 自定义 WWW-Authenticate 标头的值。
  • messagestring | object | MessageFunction - 响应体的自定义消息。

MessageFunction(c: Context) => string | object | Promise<string | object>

optional 无效的身份验证头:object

自定义身份验证标头格式无效时的错误响应。

🌐 Customizes the error response when the authentication header format is invalid.

  • wwwAuthenticateHeaderstring | object | MessageFunction - 自定义 WWW-Authenticate 标头的值。
  • messagestring | object | MessageFunction - 响应体的自定义消息。

optional 无效的令牌: object

自定义令牌无效时的错误响应。

🌐 Customizes the error response when the token is invalid.

  • wwwAuthenticateHeaderstring | object | MessageFunction - 自定义 WWW-Authenticate 标头的值。
  • messagestring | object | MessageFunction - 响应体的自定义消息。

Hono 中文网 - 粤ICP备13048890号