Skip to content

JWT Auth 中间件

¥JWT Auth Middleware

JWT Auth 中间件通过使用 JWT 验证令牌来提供身份验证。如果未设置 cookie 选项,中间件将检查 Authorization 标头。

¥The JWT Auth Middleware provides authentication by verifying the token with JWT. The middleware will check for an Authorization header if the cookie option is not set.

信息

从客户端发送的 Authorization 标头必须具有指定的方案。

¥The Authorization header sent from the client must have a specified scheme.

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

¥Example: Bearer my.token.value or Basic my.token.value

导入

¥Import

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

用法

¥Usage

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',
  })
)

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

获取有效负载:

¥Get payload:

ts
const app = new Hono()

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

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

提示

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

¥jwt() is just a middleware function. If you want to use an environment variable (eg: c.env.JWT_SECRET), you can use it as follows:

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

选项

¥Options

<徽章类型="danger" 文本="required" /> 秘密:string

¥required secret: string

你的密钥值。

¥A value of your secret key.

如果设置了此值,则使用该值作为密钥从 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 alg:string

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

¥An algorithm type that is used for verifying.\ The default is HS256.

可用的类型有 HS256 | HS384 | HS512 | RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA

¥Available types are HS256 | HS384 | HS512 | RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA.

Hono v4.7 中文网 - 粤ICP备13048890号