Skip to main content

JWT Authentication Helper

还没翻译译自英文(hono.dev)本页 46 段都还没译

模型写的

背景方法设置结果分析

JWT Authentication Helper

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.This helper provides functions for encoding, decoding, signing, and verifying JSON Web Tokens (JWTs). This helper offers robust JWT functionality with support for various cryptographic algorithms.此助手编码、解码、签名和验证 JWT JWT 用于认证与授权,因此该助手支持多种加密算法此助手编码、解码、签名和验证 JWTJWT

Import

从 hono/jwt 导入 decode、sign 和 verify

To use this helper, you can import it as follows:

import { decode, sign, verify } from 'hono/jwt'

Note

JWT Middleware also import the jwt function from the hono/jwt.JWT Middleware also import the jwt function from the hono/jwt.JWT Middleware 也从 hono/jwt 导入 jwt 它共享同一模块,因此中间件与助手放在一起JWT Middleware 也从 hono/jwt 导入 jwtJWT Middleware

sign()

sign() 编码载荷并用密钥签名

This function generates a JWT token by encoding a payload and signing it using the specified algorithm and secret.This function generates a JWT token by encoding a payload and signing it using the specified algorithm and secret.sign() 编码载荷并用算法和密钥签名 结果是签名后令牌字符串的 Promisesign() 编码载荷并用算法和密钥签名sign()

sign(
  payload: unknown,
  secret: string,
  alg?: 'HS256';

): Promise<string>;

Example

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 payload: unknown

payload:待签名的 JWT 载荷

The JWT payload to be signed. You can include other claims like in Payload Validation.The JWT payload to be signed. You can include other claims like in Payload Validation.payload 是待签名的 JWT 载荷 可以像 Payload Validation 中那样加入其他声明payload 是待签名的 JWT 载荷payload

required secret: string

secret:用于 JWT 签名或验证的密钥

The secret key used for JWT verification or signing.The secret key used for JWT verification or signing.secret 是用于 JWT 签名或验证的密钥 同一个密钥用于签名并随后验证令牌secret 是用于 JWT 签名或验证的密钥secret

optional alg: AlgorithmTypes

alg:签名或验证算法,默认 HS256

The algorithm used for JWT signing or verification. The default is HS256.The default is HS256.alg 选择签名或验证算法,默认 HS256 若省略,则默认使用基于 SHA-256 的 HMACalg 选择签名或验证算法,默认 HS256alg

verify()

verify() 检查 JWT 真实且未被篡改

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.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.verify() 检查令牌真实且有效 它检测篡改,仅在启用 Payload Validation 时校验声明verify() 检查令牌真实且有效verify()

verify(
  token: string,
  secret: string,
  alg: 'HS256';
  issuer?: string | RegExp;
  aud?: string | string[] | RegExp;
): Promise<any>;

Example

import { verify } from 'hono/jwt'

const tokenToVerify = 'token'
const secretKey = 'mySecretKey'

const decodedPayload = await verify(tokenToVerify, secretKey, 'HS256')
console.log(decodedPayload)

Options


required token: string

token:待验证的 JWT 令牌

The JWT token to be verified.The JWT token to be verified.token 是待验证的 JWT 令牌token 是待验证的 JWT 令牌token

required secret: string

secret:用于 JWT 签名或验证的密钥

The secret key used for JWT verification or signing.The secret key used for JWT verification or signing.secret 是用于 JWT 验证或签名的密钥 同一个密钥用于签名并随后验证令牌secret 是用于 JWT 验证或签名的密钥secret

required alg: AlgorithmTypes

alg:用于 JWT 签名或验证的算法

The algorithm used for JWT signing or verification.The algorithm used for JWT signing or verification.alg 是用于 JWT 签名或验证的算法alg 是用于 JWT 签名或验证的算法alg

optional issuer: string | RegExp

issuer:验证时预期的签发者

The expected issuer used for JWT verification.The expected issuer used for JWT verification.issuer 是 JWT 验证时预期的签发者 若设置,令牌的 iss 声明必须与之匹配issuer 是 JWT 验证时预期的签发者issuer

optional aud: string | string[] | RegExp

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.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.aud 要求令牌含 aud 声明且至少匹配一个值 没有匹配的受众值时,验证失败aud 要求令牌含 aud 声明且至少匹配一个值aud

decode()

decode() 不验证即返回头部和载荷

This function decodes a JWT token without performing signature verification. It extracts and returns the header and payload from the token.This function decodes a JWT token without performing signature verification. It extracts and returns the header and payload from the token.decode() 提取头部和载荷但不验证签名 它以普通对象返回这两部分decode() 提取头部和载荷但不验证签名decode()

decode(token: string): { header: any; payload: any };

Example

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 token: string

token:待解码的 JWT 令牌

The JWT token to be decoded.The JWT token to be decoded.token 是待解码的 JWT 令牌token 是待解码的 JWT 令牌token

The decode function allows you to inspect the header and payload of a JWT token without performing verification. This can be useful for debugging or extracting information from JWT tokens.

The decode function allows you to inspect the header and payload of a JWT token without performing verification. This can be useful for debugging or extracting information from JWT tokens.
decode 不做验证即可检查头部和载荷 这有助于调试或从令牌中提取信息
decode 不做验证即可检查头部和载荷
decode

Payload Validation

verify() 检查 exp、nbf、iat、iss 和 aud 声明

When verifying a JWT token, the following payload validations are performed:When verifying a JWT token, the following payload validations are performed:验证会执行以下载荷校验验证会执行以下载荷校验校验

  • exp: The token is checked to ensure it has not expired.
    exp: The token is checked to ensure it has not expired.
    检查 exp 以确保令牌尚未过期 过期令牌会被拒绝
    检查 exp 以确保令牌尚未过期
    exp
  • nbf: The token is checked to ensure it is not being used before a specified time.
    nbf: The token is checked to ensure it is not being used before a specified time.
    检查 nbf 以确保令牌未被过早使用 在指定时间前使用会被拒绝
    检查 nbf 以确保令牌未被过早使用
    nbf
  • iat: The token is checked to ensure it is not issued in the future.
    iat: The token is checked to ensure it is not issued in the future.
    检查 iat 以确保令牌不是未来签发的 未来签发的令牌会被拒绝
    检查 iat 以确保令牌不是未来签发的
    iat
  • iss: The token is checked to ensure it has been issued by a trusted issuer.
    iss: The token is checked to ensure it has been issued by a trusted issuer.
    检查 iss 以确保来自可信签发者 签发者声明必须匹配预期签发者
    检查 iss 以确保来自可信签发者
    iss
  • aud: The token is checked to ensure it is intended for an accepted audience when the aud verification parameter is set.
    aud: The token is checked to ensure it is intended for an accepted audience when the aud verification parameter is set.
    设置 aud 参数时会检查 aud 此时令牌必须面向可接受的受众
    设置 aud 参数时会检查 aud
    aud

Please ensure that your JWT payload includes these fields, as an object, if you intend to perform these checks during verification.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.The module also defines custom error types to handle JWT-related errors.该模块定义了处理 JWT 错误的自定义错误类型该模块定义了处理 JWT 错误的自定义错误类型错误类型

  • JwtAlgorithmNotImplemented: Indicates that the requested JWT algorithm is not implemented.
    JwtAlgorithmNotImplemented: Indicates that the requested JWT algorithm is not implemented.
    JwtAlgorithmNotImplemented 表示算法未实现
    JwtAlgorithmNotImplemented 表示算法未实现
    JwtAlgorithmNotImplemented
  • JwtTokenInvalid: Indicates that the JWT token is invalid.
    JwtTokenInvalid: Indicates that the JWT token is invalid.
    JwtTokenInvalid 表示 JWT 令牌无效
    JwtTokenInvalid 表示 JWT 令牌无效
    JwtTokenInvalid
  • JwtTokenNotBefore: Indicates that the token is being used before its valid date.
    JwtTokenNotBefore: Indicates that the token is being used before its valid date.
    JwtTokenNotBefore 表示在有效日期前使用
    JwtTokenNotBefore 表示在有效日期前使用
    JwtTokenNotBefore
  • JwtTokenExpired: Indicates that the token has expired.
    JwtTokenExpired: Indicates that the token has expired.
    JwtTokenExpired 表示令牌已过期
    JwtTokenExpired 表示令牌已过期
    JwtTokenExpired
  • JwtTokenIssuedAt: Indicates that the "iat" claim in the token is incorrect.
    JwtTokenIssuedAt: Indicates that the "iat" claim in the token is incorrect.
    JwtTokenIssuedAt 表示 iat 声明不正确
    JwtTokenIssuedAt 表示 iat 声明不正确
    JwtTokenIssuedAt
  • JwtTokenIssuer: Indicates that the "iss" claim in the token is incorrect.
    JwtTokenIssuer: Indicates that the "iss" claim in the token is incorrect.
    JwtTokenIssuer 表示 iss 声明不正确
    JwtTokenIssuer 表示 iss 声明不正确
    JwtTokenIssuer
  • JwtPayloadRequiresAud: Indicates that an aud claim is required when aud verification is configured.
    JwtPayloadRequiresAud: Indicates that an aud claim is required when aud verification is configured.
    JwtPayloadRequiresAud 表示缺少必需的 aud 声明
    JwtPayloadRequiresAud 表示缺少必需的 aud 声明
    JwtPayloadRequiresAud
  • JwtTokenAudience: Indicates that the token's aud claim does not match the expected audience.
    JwtTokenAudience: Indicates that the token's aud claim does not match the expected audience.
    JwtTokenAudience 表示 aud 声明不匹配
    JwtTokenAudience 表示 aud 声明不匹配
    JwtTokenAudience
  • JwtTokenSignatureMismatched: Indicates a signature mismatch in the token.
    JwtTokenSignatureMismatched: Indicates a signature mismatch in the token.
    JwtTokenSignatureMismatched 表示签名不匹配
    JwtTokenSignatureMismatched 表示签名不匹配
    JwtTokenSignatureMismatched

Supported AlgorithmTypes

支持的算法包括 HS、RS、PS、ES 和 EdDSA

The module supports the following JWT cryptographic algorithms:The module supports the following JWT cryptographic algorithms:该模块支持以下 JWT 加密算法该模块支持以下 JWT 加密算法算法

  • HS256: HMAC using SHA-256
    HS256: HMAC using SHA-256
    HS256 是使用 SHA-256 的 HMAC
    HS256 是使用 SHA-256 的 HMAC
    HS256
  • HS384: HMAC using SHA-384
    HS384: HMAC using SHA-384
    HS384 是使用 SHA-384 的 HMAC
    HS384 是使用 SHA-384 的 HMAC
    HS384
  • HS512: HMAC using SHA-512
    HS512: HMAC using SHA-512
    HS512 是使用 SHA-512 的 HMAC
    HS512 是使用 SHA-512 的 HMAC
    HS512
  • RS256: RSASSA-PKCS1-v1_5 using SHA-256
    RS256: RSASSA-PKCS1-v1_5 using SHA-256
    RS256 是使用 SHA-256 的 RSASSA-PKCS1-v1_5
    RS256 是使用 SHA-256 的 RSASSA-PKCS1-v1_5
    RS256
  • RS384: RSASSA-PKCS1-v1_5 using SHA-384
    RS384: RSASSA-PKCS1-v1_5 using SHA-384
    RS384 是使用 SHA-384 的 RSASSA-PKCS1-v1_5
    RS384 是使用 SHA-384 的 RSASSA-PKCS1-v1_5
    RS384
  • RS512: RSASSA-PKCS1-v1_5 using SHA-512
    RS512: RSASSA-PKCS1-v1_5 using SHA-512
    RS512 是使用 SHA-512 的 RSASSA-PKCS1-v1_5
    RS512 是使用 SHA-512 的 RSASSA-PKCS1-v1_5
    RS512
  • PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256
    PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256
    PS256 是使用 SHA-256 和 MGF1 的 RSASSA-PSS
    PS256 是使用 SHA-256 和 MGF1 的 RSASSA-PSS
    PS256
  • PS384: RSASSA-PSS using SHA-386 and MGF1 with SHA-386
    PS384: RSASSA-PSS using SHA-386 and MGF1 with SHA-386
    PS384 是使用 SHA-384 和 MGF1 的 RSASSA-PSS
    PS384 是使用 SHA-384 和 MGF1 的 RSASSA-PSS
    PS384
  • PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512
    PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512
    PS512 是使用 SHA-512 和 MGF1 的 RSASSA-PSS
    PS512 是使用 SHA-512 和 MGF1 的 RSASSA-PSS
    PS512
  • ES256: ECDSA using P-256 and SHA-256
    ES256: ECDSA using P-256 and SHA-256
    ES256 是使用 P-256 和 SHA-256 的 ECDSA
    ES256 是使用 P-256 和 SHA-256 的 ECDSA
    ES256
  • ES384: ECDSA using P-384 and SHA-384
    ES384: ECDSA using P-384 and SHA-384
    ES384 是使用 P-384 和 SHA-384 的 ECDSA
    ES384 是使用 P-384 和 SHA-384 的 ECDSA
    ES384
  • ES512: ECDSA using P-521 and SHA-512
    ES512: ECDSA using P-521 and SHA-512
    ES512 是使用 P-521 和 SHA-512 的 ECDSA
    ES512 是使用 P-521 和 SHA-512 的 ECDSA
    ES512
  • EdDSA: EdDSA using Ed25519
    EdDSA: EdDSA using Ed25519
    EdDSA 是使用 Ed25519 的 EdDSA
    EdDSA 是使用 Ed25519 的 EdDSA
    EdDSA