跳转到正文

JWT Auth 中间件 ​

JWT Auth 中间件通过验证 JWT 令牌提供身份验证。 未设置 cookie 选项时,中间件会检查 Authorization 请求头。可以通过 headerName 选项自定义头部名称。

说明

客户端发送的 Authorization 请求头必须包含指定的身份验证方案。

示例:Bearer my.token.value 或 Basic my.token.value

导入 ​

ts
import { Hono } from 'hono'
import { jwt } from 'hono/jwt'
import type { JwtVariables } from 'hono/jwt'

用法 ​

ts
// Specify the variable types to infer the `c.get('jwtPayload')`:
type Variables = JwtVariables

const app = new Hono<{ Variables: Variables }>()

app.use(
  '/auth/*',
  jwt({
    secret: 'it-is-very-secret',
    alg: 'HS256',
  })
)

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

获取载荷:

ts
const app = new Hono()

app.use(
  '/auth/*',
  jwt({
    secret: 'it-is-very-secret',
    alg: 'HS256',
    verification: {
      iss: 'my-trusted-issuer',
      aud: 'my-api',
    },
  })
)

app.get('/auth/page', (c) => {
  const payload = c.get('jwtPayload')
  return c.json(payload) // eg: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022, "iss": "my-trusted-issuer" }
})

提示

jwt() 只是一个中间件函数。如果要使用环境变量(例如 c.env.JWT_SECRET),可以按以下方式使用:

js
app.use('/auth/*', (c, next) => {
  const jwtMiddleware = jwt({
    secret: c.env.JWT_SECRET,
    alg: 'HS256',
  })
  return jwtMiddleware(c, next)
})

选项 ​

required secret: string ​

密钥的值。

required alg: string ​

用于验证的算法类型。

可用类型包括 HS256 | HS384 | HS512 | RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA。

设置此值后,会以它为键从 cookie 请求头中获取对应值,再将该值作为令牌进行验证。

optional headerName: string ​

查找 JWT 令牌的请求头名称。默认值为 Authorization。

ts
app.use(
  '/auth/*',
  jwt({
    secret: 'it-is-very-secret',
    alg: 'HS256',
    headerName: 'x-custom-auth-header',
  })
)

optional realm: string ​

在 401 响应返回的 WWW-Authenticate 质询头中,由 realm 参数描述的保护域。默认值为请求 URL。

ts
app.use(
  '/auth/*',
  jwt({
    secret: 'it-is-very-secret',
    realm: 'my-protected-api',
  })
)

optional verification: VerifyOptions ​

控制令牌验证的选项。

optional VerifyOptions.iss: string | RegExp ​

验证令牌时预期的签发者。未设置时,不会检查 iss 声明。

optional VerifyOptions.aud: string | string[] | RegExp ​

验证令牌时预期的受众。设置后,令牌必须包含 aud 声明,且至少一个受众值必须匹配。

optional VerifyOptions.nbf: boolean ​

nbf(生效时间)声明存在且此项设为 true 时,会验证该声明。默认值为 true。

optional VerifyOptions.iat: boolean ​

iat(签发时间)声明存在且此项设为 true 时,会验证该声明。默认值为 true。

optional VerifyOptions.exp: boolean ​

exp(过期时间)声明存在且此项设为 true 时,会验证该声明。默认值为 true。

基于 MIT 许可证发布。