JWT Authentication Helper
Model-written
contextmethodsetupresultanalysis
JWT Authentication Helper
JWT helper encodes, signs, verifies and decodes tokens
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.This helper encodes, decodes, signs and verifies JWTs JWTs serve authentication and authorization, so the helper supports several cryptographic algorithmsThis helper encodes, decodes, signs and verifies JWTsJWTs
Import
Import decode, sign and verify from hono/jwt
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 also imports jwt from hono/jwt It shares the same module, so the middleware and helper live togetherJWT Middleware also imports jwt from hono/jwtJWT Middleware
sign()
sign() encodes a payload and signs it with a secret
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() encodes a payload and signs it with algorithm and secret The result is a Promise of the signed token stringsign() encodes a payload and signs it with algorithm and secretsign()
sign(
payload: unknown,
secret: string,
alg?: 'HS256';
): Promise<string>;Options
required payload: unknown
payload: the JWT payload to be signed
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 is the JWT payload to be signed You can include other claims, as described under Payload Validationpayload is the JWT payload to be signedpayload
required secret: string
secret: the key used for JWT signing or verification
The secret key used for JWT verification or signing.The secret key used for JWT verification or signing.secret is the key used for JWT signing or verification The same key is used to sign and later verify tokenssecret is the key used for JWT signing or verificationsecret
optional alg: AlgorithmTypes
alg: the signing or verification algorithm, default HS256
The algorithm used for JWT signing or verification. The default is HS256.The default is HS256.alg selects the signing or verification algorithm, default HS256 If omitted, HMAC using SHA-256 is assumedalg selects the signing or verification algorithm, default HS256alg
verify()
verify() checks a JWT is genuine and unaltered
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() checks a token is genuine and valid It detects tampering, and validates claims only when Payload Validation is usedverify() checks a token is genuine and validverify()
verify(
token: string,
secret: string,
alg: 'HS256';
issuer?: string | RegExp;
aud?: string | string[] | RegExp;
): Promise<any>;
Options
required token: string
token: the JWT token to be verified
The JWT token to be verified.The JWT token to be verified.token is the JWT token to be verifiedtoken is the JWT token to be verifiedtoken
required secret: string
secret: the key used for JWT signing or verification
The secret key used for JWT verification or signing.The secret key used for JWT verification or signing.secret is the key used for JWT verification or signing The same key is used to sign and later verify tokenssecret is the key used for JWT verification or signingsecret
required alg: AlgorithmTypes
alg: the algorithm used for JWT signing or verification
The algorithm used for JWT signing or verification.The algorithm used for JWT signing or verification.alg is the algorithm used for JWT signing or verificationalg is the algorithm used for JWT signing or verificationalg
optional issuer: string | RegExp
issuer: the expected issuer used for verification
The expected issuer used for JWT verification.The expected issuer used for JWT verification.issuer is the expected issuer used for JWT verification If set, the token's iss claim must match itissuer is the expected issuer used for JWT verificationissuer
optional aud: string | string[] | RegExp
aud: expected audience, at least one 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.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 requires an aud claim matching at least one value Without a matching audience value, verification failsaud requires an aud claim matching at least one valueaud
decode()
decode() returns header and payload without verifying
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() extracts header and payload without verifying the signature It returns both parts as a plain objectdecode() extracts header and payload without verifying the signaturedecode()
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: the JWT token to be decoded
The JWT token to be decoded.The JWT token to be decoded.token is the JWT token to be decodedtoken is the JWT token to be decodedtoken
The
decodefunction 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.Thedecodefunction 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 inspects header and payload without verification This helps debug or extract information from tokensdecode inspects header and payload without verificationdecode
Payload Validation
verify() checks exp, nbf, iat, iss and aud claims
When verifying a JWT token, the following payload validations are performed:When verifying a JWT token, the following payload validations are performed:Verification performs the following payload validationsVerification performs the following payload validationsvalidations
exp: The token is checked to ensure it has not expired.exp: The token is checked to ensure it has not expired.exp is checked to ensure the token has not expired An expired token is rejectedexp is checked to ensure the token has not expiredexpnbf: 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 is checked to ensure the token is not used too early Use before the specified time is rejectednbf is checked to ensure the token is not used too earlynbfiat: 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 is checked to ensure the token is not future-issued A token issued in the future is rejectediat is checked to ensure the token is not future-issuediatiss: 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 is checked to ensure a trusted issuer The issuer claim must match the expected issueriss is checked to ensure a trusted issuerissaud: The token is checked to ensure it is intended for an accepted audience when theaudverification parameter is set.aud: The token is checked to ensure it is intended for an accepted audience when theaudverification parameter is set.aud is checked when the aud parameter is set The token must then be intended for an accepted audienceaud is checked when the aud parameter is setaud
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.Include these claims in the payload object for checks Without them, the corresponding validations are skippedInclude these claims in the payload object for checksclaims
Custom Error Types
Custom error types cover JWT algorithm, token and claim failures
The module also defines custom error types to handle JWT-related errors.The module also defines custom error types to handle JWT-related errors.The module defines custom error types for JWT errorsThe module defines custom error types for JWT errorserror types
JwtAlgorithmNotImplemented: Indicates that the requested JWT algorithm is not implemented.JwtAlgorithmNotImplemented: Indicates that the requested JWT algorithm is not implemented.JwtAlgorithmNotImplemented signals an unimplemented algorithmJwtAlgorithmNotImplemented signals an unimplemented algorithmJwtAlgorithmNotImplementedJwtTokenInvalid: Indicates that the JWT token is invalid.JwtTokenInvalid: Indicates that the JWT token is invalid.JwtTokenInvalid signals an invalid JWT tokenJwtTokenInvalid signals an invalid JWT tokenJwtTokenInvalidJwtTokenNotBefore: Indicates that the token is being used before its valid date.JwtTokenNotBefore: Indicates that the token is being used before its valid date.JwtTokenNotBefore signals use before the valid dateJwtTokenNotBefore signals use before the valid dateJwtTokenNotBeforeJwtTokenExpired: Indicates that the token has expired.JwtTokenExpired: Indicates that the token has expired.JwtTokenExpired signals an expired tokenJwtTokenExpired signals an expired tokenJwtTokenExpiredJwtTokenIssuedAt: Indicates that the "iat" claim in the token is incorrect.JwtTokenIssuedAt: Indicates that the "iat" claim in the token is incorrect.JwtTokenIssuedAt signals an incorrect iat claimJwtTokenIssuedAt signals an incorrect iat claimJwtTokenIssuedAtJwtTokenIssuer: Indicates that the "iss" claim in the token is incorrect.JwtTokenIssuer: Indicates that the "iss" claim in the token is incorrect.JwtTokenIssuer signals an incorrect iss claimJwtTokenIssuer signals an incorrect iss claimJwtTokenIssuerJwtPayloadRequiresAud: Indicates that anaudclaim is required whenaudverification is configured.JwtPayloadRequiresAud: Indicates that anaudclaim is required whenaudverification is configured.JwtPayloadRequiresAud signals a required aud claim is missingJwtPayloadRequiresAud signals a required aud claim is missingJwtPayloadRequiresAudJwtTokenAudience: Indicates that the token'saudclaim does not match the expected audience.JwtTokenAudience: Indicates that the token'saudclaim does not match the expected audience.JwtTokenAudience signals the aud claim does not matchJwtTokenAudience signals the aud claim does not matchJwtTokenAudienceJwtTokenSignatureMismatched: Indicates a signature mismatch in the token.JwtTokenSignatureMismatched: Indicates a signature mismatch in the token.JwtTokenSignatureMismatched signals a signature mismatchJwtTokenSignatureMismatched signals a signature mismatchJwtTokenSignatureMismatched
Supported AlgorithmTypes
Supized algorithms include HS, RS, PS, ES and EdDSA
The module supports the following JWT cryptographic algorithms:The module supports the following JWT cryptographic algorithms:The module supports these JWT cryptographic algorithmsThe module supports these JWT cryptographic algorithmsalgorithms
HS256: HMAC using SHA-256HS256: HMAC using SHA-256HS256 is HMAC using SHA-256HS256 is HMAC using SHA-256HS256HS384: HMAC using SHA-384HS384: HMAC using SHA-384HS384 is HMAC using SHA-384HS384 is HMAC using SHA-384HS384HS512: HMAC using SHA-512HS512: HMAC using SHA-512HS512 is HMAC using SHA-512HS512 is HMAC using SHA-512HS512RS256: RSASSA-PKCS1-v1_5 using SHA-256RS256: RSASSA-PKCS1-v1_5 using SHA-256RS256 is RSASSA-PKCS1-v1_5 using SHA-256RS256 is RSASSA-PKCS1-v1_5 using SHA-256RS256RS384: RSASSA-PKCS1-v1_5 using SHA-384RS384: RSASSA-PKCS1-v1_5 using SHA-384RS384 is RSASSA-PKCS1-v1_5 using SHA-384RS384 is RSASSA-PKCS1-v1_5 using SHA-384RS384RS512: RSASSA-PKCS1-v1_5 using SHA-512RS512: RSASSA-PKCS1-v1_5 using SHA-512RS512 is RSASSA-PKCS1-v1_5 using SHA-512RS512 is RSASSA-PKCS1-v1_5 using SHA-512RS512PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256PS256 is RSASSA-PSS using SHA-256 and MGF1PS256 is RSASSA-PSS using SHA-256 and MGF1PS256PS384: RSASSA-PSS using SHA-386 and MGF1 with SHA-386PS384: RSASSA-PSS using SHA-386 and MGF1 with SHA-386PS384 is RSASSA-PSS using SHA-384 and MGF1PS384 is RSASSA-PSS using SHA-384 and MGF1PS384PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512PS512 is RSASSA-PSS using SHA-512 and MGF1PS512 is RSASSA-PSS using SHA-512 and MGF1PS512ES256: ECDSA using P-256 and SHA-256ES256: ECDSA using P-256 and SHA-256ES256 is ECDSA using P-256 and SHA-256ES256 is ECDSA using P-256 and SHA-256ES256ES384: ECDSA using P-384 and SHA-384ES384: ECDSA using P-384 and SHA-384ES384 is ECDSA using P-384 and SHA-384ES384 is ECDSA using P-384 and SHA-384ES384ES512: ECDSA using P-521 and SHA-512ES512: ECDSA using P-521 and SHA-512ES512 is ECDSA using P-521 and SHA-512ES512 is ECDSA using P-521 and SHA-512ES512EdDSA: EdDSA using Ed25519EdDSA: EdDSA using Ed25519EdDSA is EdDSA using Ed25519EdDSA is EdDSA using Ed25519EdDSA