Appearance
Bearer Auth 中间件
¥Bearer Auth Middleware
Bearer Auth Middleware 通过验证 Request 标头中的 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
你的 `token` 必须与正则表达式 `/[A-Za-z0-9._~+/-]+=*/` 匹配,否则将返回 400 错误。值得注意的是,此正则表达式同时适用于 URL 安全的 Base64 和标准 Base64 编码的 JWT。此中间件不需要承载令牌是 JWT,只需要它与上述正则表达式匹配。
¥[!NOTE] Your token must match the regex /[A-Za-z0-9._~+/-]+=*/, otherwise a 400 error will be returned. Notably, this regex acommodates both URL-safe Base64- and standard Base64-encoded JWTs. This middleware does not require the bearer token to be a JWT, just that it matches the above regex.
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.如果你想自己验证 token 的值,请指定 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
<徽章类型="danger" 文本="required" /> 令牌:string | string[]
¥required token: string | string[]
用于验证传入 bearer 令牌的字符串。
¥The string to validate the incoming bearer token against.
<徽章类型="info" 文本="optional" /> 字段:string
¥optional realm: 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 prefix:string
授权标头值的前缀(或称为 schema)。默认为 "Bearer"。
¥The prefix (or known as schema) for the Authorization header value. The default is "Bearer".
optional 标头名称:string
¥optional headerName: string
标头名称。默认值为 Authorization。
¥The header name. The default value is Authorization.
optional hashFunction:Function
用于处理哈希函数以安全地比较身份验证令牌的函数。
¥A function to handle hashing for safe comparison of authentication tokens.
optional verifyToken:(token: string, c: Context) => boolean | Promise<boolean>
验证令牌的函数。
¥The function to verify the token.
optional noAuthenticationHeaderMessage:string | object | MessageFunction
MessageFunction 是 (c: Context) => string | object | Promise<string | object>。如果没有身份验证标头,则显示自定义消息。
¥MessageFunction is (c: Context) => string | object | Promise<string | object>. The custom message if it does not have an authentication header.
optional invalidAuthenticationHeaderMessage:string | object | MessageFunction
如果身份验证标头无效,则显示自定义消息。
¥The custom message if the authentication header is invalid.
optional invalidTokenMessage:string | object | MessageFunction
如果令牌无效,则显示自定义消息。
¥The custom message if the token is invalid.