Appearance
JWT 身份验证助手
🌐 JWT Authentication Helper
此助手提供用于编码、解码、签名和验证 JSON Web 令牌(JWT)的功能。JWT 通常用于 Web 应用中的身份验证和授权目的。此助手提供强大的 JWT 功能,并支持多种加密算法。
🌐 This helper provides functions for encoding, decoding, signing, and verifying JSON Web Tokens (JWTs). JWTs are commonly used for authentication and authorization purposes in web applications. This helper offers robust JWT functionality with support for various cryptographic algorithms.
导入
🌐 Import
要使用此辅助程序,你可以按如下方式导入它:
🌐 To use this helper, you can import it as follows:
ts
import { decode, sign, verify } from 'hono/jwt'INFO
JWT 中间件 还从 hono/jwt 导入了 jwt 函数。
sign()
此函数通过编码有效负载并使用指定的算法和密钥对其进行签名来生成 JWT 令牌。
🌐 This function generates a JWT token by encoding a payload and signing it using the specified algorithm and secret.
ts
sign(
payload: unknown,
secret: string,
alg?: 'HS256';
): Promise<string>;示例
🌐 Example
ts
import { sign } from 'hono/jwt'
const payload = {
sub: 'user123',
role: 'admin',
exp: Math.floor(Date.now() / 1000) + 60 * 5, // Token expires in 5 minutes
}
const secret = 'mySecretKey'
const token = await sign(payload, secret)选项
🌐 Options
required 有效载荷: unknown
要签名的 JWT 有效负载。你可以像在 Payload Validation 中那样包含其他声明。
🌐 The JWT payload to be signed. You can include other claims like in Payload Validation.
required 秘密:string
用于 JWT 验证或签名的密钥。
🌐 The secret key used for JWT verification or signing.
optional alg: 算法类型
用于 JWT 签名或验证的算法。默认是 HS256。
🌐 The algorithm used for JWT signing or verification. The default is HS256.
verify()
此函数检查 JWT 令牌是否真实且仍然有效。它确保令牌未被篡改,并且仅在你添加了 Payload Validation 时检查有效性。
🌐 This function checks if a JWT token is genuine and still valid. It ensures the token hasn't been altered and checks validity only if you added Payload Validation.
ts
verify(
token: string,
secret: string,
alg: 'HS256';
issuer?: string | RegExp;
aud?: string | string[] | RegExp;
): Promise<any>;示例
🌐 Example
ts
import { verify } from 'hono/jwt'
const tokenToVerify = 'token'
const secretKey = 'mySecretKey'
const decodedPayload = await verify(tokenToVerify, secretKey, 'HS256')
console.log(decodedPayload)选项
🌐 Options
required 令牌: string
要验证的 JWT 令牌。
🌐 The JWT token to be verified.
required 秘密:string
用于 JWT 验证或签名的密钥。
🌐 The secret key used for JWT verification or signing.
required alg: 算法类型
用于 JWT 签名或验证的算法。
🌐 The algorithm used for JWT signing or verification.
optional 发行者: string | RegExp
用于 JWT 验证的预期发行者。
🌐 The expected issuer used for JWT verification.
optional aud: string | string[] | RegExp
用于 JWT 验证的预期受众。如果设置了此项,令牌必须包含 aud 声明,并且至少有一个受众值必须匹配。
🌐 The expected audience used for JWT verification. If this is set, the token must include an aud claim and at least one audience value must match.
decode()
此函数解码 JWT 令牌而不执行签名验证。它从令牌中提取并返回头部和负载。
🌐 This function decodes a JWT token without performing signature verification. It extracts and returns the header and payload from the token.
ts
decode(token: string): { header: any; payload: any };示例
🌐 Example
ts
import { decode } from 'hono/jwt'
// Decode the JWT token
const tokenToDecode =
'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiOiAidXNlcjEyMyIsICJyb2xlIjogImFkbWluIn0.JxUwx6Ua1B0D1B0FtCrj72ok5cm1Pkmr_hL82sd7ELA'
const { header, payload } = decode(tokenToDecode)
console.log('Decoded Header:', header)
console.log('Decoded Payload:', payload)选项
🌐 Options
required 令牌: string
要解码的 JWT 令牌。
🌐 The JWT token to be decoded.
decode函数允许你在 不 执行验证的情况下检查 JWT 令牌的头部和负载。这对于调试或从 JWT 令牌中提取信息非常有用。
有效负载验证
🌐 Payload Validation
验证 JWT 令牌时,将执行以下有效负载验证:
🌐 When verifying a JWT token, the following payload validations are performed:
exp:检查令牌以确保其未过期。nbf:检查令牌以确保其未在指定时间之前被使用。iat:检查令牌以确保其不会在将来发出。iss:检查令牌以确保其由受信任的发行者发行。aud:当设置aud验证参数时,会检查令牌以确保其面向的是一个被接受的受众。
如果你打算在验证期间执行这些检查,请确保你的 JWT 有效负载包含这些字段作为对象。
🌐 Please ensure that your JWT payload includes these fields, as an object, if you intend to perform these checks during verification.
自定义错误类型
🌐 Custom Error Types
该模块还定义了自定义错误类型来处理与 JWT 相关的错误。
🌐 The module also defines custom error types to handle JWT-related errors.
JwtAlgorithmNotImplemented:表示请求的 JWT 算法未实现。JwtTokenInvalid:表示 JWT 令牌无效。JwtTokenNotBefore:表示令牌在有效期之前使用。JwtTokenExpired:表示令牌已过期。JwtTokenIssuedAt:表示令牌中的“iat”声明不正确。JwtTokenIssuer:表示令牌中的“iss”声明不正确。JwtPayloadRequiresAud:指示在配置了aud验证时需要aud声明。JwtTokenAudience:表示令牌的aud声明与预期受众不匹配。JwtTokenSignatureMismatched:表示令牌中的签名不匹配。
支持的算法类型
🌐 Supported AlgorithmTypes
该模块支持以下 JWT 加密算法:
🌐 The module supports the following JWT cryptographic algorithms:
HS256:使用 SHA-256 的 HMACHS384:使用 SHA-384 的 HMACHS512:使用 SHA-512 的 HMACRS256:使用 SHA-256 的 RSASSA-PKCS1-v1_5RS384:使用 SHA-384 的 RSASSA-PKCS1-v1_5RS512:使用 SHA-512 的 RSASSA-PKCS1-v1_5PS256:RSASSA-PSS 使用 SHA-256 和 MGF1 使用 SHA-256PS384:RSASSA-PSS 使用 SHA-386 和 MGF1 使用 SHA-386PS512:RSASSA-PSS 使用 SHA-512 和 MGF1 使用 SHA-512ES256:使用 P-256 和 SHA-256 的 ECDSAES384:使用 P-384 和 SHA-384 的 ECDSAES512:使用 P-521 和 SHA-512 的 ECDSAEdDSA:使用 Ed25519 的 EdDSA