Appearance
JWK Auth 中间件
🌐 JWK Auth Middleware
JWK 认证中间件通过使用 JWK(JSON Web Key)验证令牌来对请求进行身份验证。它会检查 Authorization 头以及其他配置的来源(如果指定的话),例如 Cookie。它使用提供的 keys 验证令牌,如果指定的话从 jwks_uri 检索密钥,并且如果设置了 cookie 选项,还支持从 Cookie 中提取令牌。
🌐 The JWK Auth Middleware authenticates requests by verifying tokens using JWK (JSON Web Key). It checks for an Authorization header and other configured sources, such as cookies, if specified. It validates tokens using the provided keys, retrieves keys from jwks_uri if specified, and supports token extraction from cookies if the cookie option is set.
这个中间件验证什么
🌐 What this middleware validates
对于每个标记,jwk():
🌐 For each token, jwk():
- 解析并验证 JWT 头部格式。
- 需要一个
kid头,并通过kid找到匹配的密钥。 - 拒绝对称算法(
HS256、HS384、HS512)。 - 要求在配置的
alg允许列表中包含头部alg。 - 如果匹配的 JWK 有一个
alg字段,则要求它与 JWT 头部的alg匹配。 - 使用匹配的密钥验证令牌签名。
- 默认情况下,验证基于时间的声明:
nbf、exp和iat。
可通过 verification 选项配置可选的声明验证:
🌐 Optional claim validation can be configured with the verification option:
iss:在提供时验证发行者。aud:在提供时验证受众。
如果你需要除了上述之外的额外令牌检查(例如,自定义的应用级授权规则),请在 jwk() 之后的自定义中间件中添加它们。
🌐 If you need additional token checks beyond the above (for example, custom application-level authorization rules), add them in your own middleware after jwk().
INFO
从客户端发送的 Authorization 标头必须具有指定的方案。
示例:Bearer my.token.value 或 Basic my.token.value
🌐 Example: Bearer my.token.value or Basic my.token.value :::
导入
🌐 Import
ts
import { Hono } from 'hono'
import { jwk } from 'hono/jwk'
import { verifyWithJwks } from 'hono/jwt'用法
🌐 Usage
ts
const app = new Hono()
app.use(
'/auth/*',
jwk({
jwks_uri: `https://${backendServer}/.well-known/jwks.json`,
alg: ['RS256'],
})
)
app.get('/auth/page', (c) => {
return c.text('You are authorized')
})获取有效负载:
🌐 Get payload:
ts
const app = new Hono()
app.use(
'/auth/*',
jwk({
jwks_uri: `https://${backendServer}/.well-known/jwks.json`,
alg: ['RS256'],
})
)
app.get('/auth/page', (c) => {
const payload = c.get('jwtPayload')
return c.json(payload) // eg: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
})匿名访问:
🌐 Anonymous access:
ts
const app = new Hono()
app.use(
'/auth/*',
jwk({
jwks_uri: (c) =>
`https://${c.env.authServer}/.well-known/jwks.json`,
alg: ['RS256'],
allow_anon: true,
})
)
app.get('/auth/page', (c) => {
const payload = c.get('jwtPayload')
return c.json(payload ?? { message: 'hello anon' })
})在中间件之外使用 verifyWithJwks
🌐 Using verifyWithJwks outside of middleware
verifyWithJwks 实用函数可以用于在 Hono 的中间件环境之外验证 JWT 令牌,例如在 SvelteKit SSR 页面或其他服务器端环境中:
🌐 The verifyWithJwks utility function can be used to verify JWT tokens outside of Hono's middleware context, such as in SvelteKit SSR pages or other server-side environments:
ts
const id_payload = await verifyWithJwks(
id_token,
{
jwks_uri: 'https://your-auth-server/.well-known/jwks.json',
allowedAlgorithms: ['RS256'],
},
{
cf: { cacheEverything: true, cacheTtl: 3600 },
}
)配置 JWKS 获取请求选项
🌐 Configuring JWKS fetch request options
要配置如何从 jwks_uri 检索 JWKS,请将获取请求选项作为 jwk() 的第二个参数传递。
🌐 To configure how JWKS is retrieved from jwks_uri, pass fetch request options as the second argument of jwk().
此参数是 RequestInit,仅用于 JWKS 获取请求。
🌐 This argument is RequestInit and is used only for the JWKS fetch request.
ts
const app = new Hono()
app.use(
'/auth/*',
jwk(
{
jwks_uri: `https://${backendServer}/.well-known/jwks.json`,
alg: ['RS256'],
},
{
headers: {
Authorization: 'Bearer TOKEN',
},
}
)
)选项
🌐 Options
required 算法: AsymmetricAlgorithm[]
用于令牌验证的允许的不对称算法数组。
🌐 An array of allowed asymmetric algorithms used for token verification.
可用类型有 RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA。
🌐 Available types are RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA.
optional 键:HonoJsonWebKey[] | (c: Context) => Promise<HonoJsonWebKey[]>
你的公钥的值,或者返回它们的函数。该函数接收 Context 对象。
🌐 The values of your public keys, or a function that returns them. The function receives the Context object.
optional jwks_uri: string | (c: Context) => Promise<string>
如果设置了此值,将尝试从此 URI 获取 JWK,预期返回的 JSON 中包含 keys,这些将被添加到提供的 keys 选项中。你也可以传递一个回调函数,使用上下文动态确定 JWKS URI。
🌐 If this value is set, attempt to fetch JWKs from this URI, expecting a JSON response with keys, which are added to the provided keys option. You can also pass a callback function to dynamically determine the JWKS URI using the Context.
optional 允许匿名:boolean
如果此值设置为 true,没有有效令牌的请求将被允许通过中间件。使用 c.get('jwtPayload') 来检查请求是否经过身份验证。默认值是 false。
🌐 If this value is set to true, requests without a valid token will be allowed to pass through the middleware. Use c.get('jwtPayload') to check if the request is authenticated. The default is false.
optional cookie: string
如果设置了此值,则使用该值作为密钥从 cookie 标头中检索该值,然后将其验证为令牌。
🌐 If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.
optional headerName: string
要查找 JWT 令牌的头名称。默认值是 Authorization。
🌐 The name of the header to look for the JWT token. The default is Authorization.
optional 验证:VerifyOptions
除了签名验证外,还要配置声明验证行为:
🌐 Configure claim validation behavior in addition to signature verification:
optional VerifyOptions.iss: string | RegExp
用于令牌验证的预期发行者。如果未设置此项,将不会检查 iss 声明。
🌐 The expected issuer used for token verification. The iss claim will not be checked if this isn't set.
optional VerifyOptions.aud: string | string[] | RegExp
用于令牌验证的预期受众。如果设置了此项,令牌必须包含 aud 声明,并且至少有一个受众值必须匹配。
🌐 The expected audience used for token verification. If this is set, the token must include an aud claim and at least one audience value must match.
optional VerifyOptions.nbf: boolean
如果存在,nbf(不可早于)声明将被验证,并且设置为 true。默认值是 true。
🌐 The nbf (not before) claim will be verified if present and this is set to true. The default is true.
optional VerifyOptions.iat: boolean
iat(签发时间)声明如果存在将会被验证,并且其值设置为 true。默认值是 true。
🌐 The iat (issued at) claim will be verified if present and this is set to true. The default is true.
optional VerifyOptions.exp: boolean
exp(过期时间)声明如果存在将会被验证,并且其设置为 true。默认值是 true。
🌐 The exp (expiration time) claim will be verified if present and this is set to true. The default is true.