JWT 身份验证中间件
JWT 身份验证中间件通过使用 JWT 验证令牌来提供身份验证。如果未设置 cookie 选项,则中间件将检查 Authorization 标头。
信息
客户端发送的 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',
})
)
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',
})
)
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),您可以按如下方式使用它
js
app.use('/auth/*', (c, next) => {
const jwtMiddleware = jwt({
secret: c.env.JWT_SECRET,
})
return jwtMiddleware(c, next)
})选项
必需 secret: string
您的密钥的价值。
可选 cookie: string
如果设置了此值,则该值将从使用该值作为键的 Cookie 标头中检索,然后将其验证为令牌。
可选 alg: string
用于验证的算法类型。
默认值为 HS256。
可用的类型为 HS256 | HS384 | HS512 | RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA。
