Skip to content

JWT Auth 中间件

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

INFO

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

例如:Bearer my.token.valueBasic my.token.value

导入

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

用法

ts
// 指定变量类型,以便推断 `c.get('jwtPayload')`:
type Variables = JwtVariables

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

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

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

获取 payload:

ts
const app = new Hono()

app.use(
  '/auth/*',
  jwt({
    secret: 'it-is-very-secret',
    issuer: 'my-trusted-issuer',
  })
)

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

TIP

jwt() 只是一个中间件函数。如果需要使用环境变量(例如 c.env.JWT_SECRET),可以这样写:

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

选项

required secret:string

用于签名的密钥。

若设置该值,将使用对应键名从 Cookie 头中提取令牌并进行验证。

optional alg:string

用于验证的算法类型,默认值为 HS256

可用算法包括:HS256 | HS384 | HS512 | RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA

optional headerName:string

要读取 JWT 的请求头名称,默认是 Authorization

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

optional verifyOptions:VerifyOptions

用于控制令牌验证的选项。

optional verifyOptions.iss:string | RegExp

期望的发行者(issuer)。若未设置,则不会校验 iss 声明。

optional verifyOptions.nbf:boolean

当设置为 true 时,如果令牌包含 nbf(not before)声明,将进行校验。默认值为 true

optional verifyOptions.iat:boolean

当设置为 true 时,如果令牌包含 iat(issued at)声明,将进行校验。默认值为 true

optional verifyOptions.exp:boolean

当设置为 true 时,如果令牌包含 exp(expiration)声明,将进行校验。默认值为 true

Released under the MIT License.