Skip to main content

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>;

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: 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>;

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: 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 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 inspects header and payload without verification This helps debug or extract information from tokens
decode inspects header and payload without verification
decode

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 rejected
    exp is checked to ensure the token has not expired
    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 is checked to ensure the token is not used too early Use before the specified time is rejected
    nbf is checked to ensure the token is not used too early
    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 is checked to ensure the token is not future-issued A token issued in the future is rejected
    iat is checked to ensure the token is not future-issued
    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 is checked to ensure a trusted issuer The issuer claim must match the expected issuer
    iss is checked to ensure a trusted issuer
    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 is checked when the aud parameter is set The token must then be intended for an accepted audience
    aud is checked when the aud parameter is set
    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.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 algorithm
    JwtAlgorithmNotImplemented signals an unimplemented algorithm
    JwtAlgorithmNotImplemented
  • JwtTokenInvalid: Indicates that the JWT token is invalid.
    JwtTokenInvalid: Indicates that the JWT token is invalid.
    JwtTokenInvalid signals an invalid JWT token
    JwtTokenInvalid signals an invalid JWT token
    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 signals use before the valid date
    JwtTokenNotBefore signals use before the valid date
    JwtTokenNotBefore
  • JwtTokenExpired: Indicates that the token has expired.
    JwtTokenExpired: Indicates that the token has expired.
    JwtTokenExpired signals an expired token
    JwtTokenExpired signals an expired token
    JwtTokenExpired
  • JwtTokenIssuedAt: 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 claim
    JwtTokenIssuedAt signals an incorrect iat claim
    JwtTokenIssuedAt
  • JwtTokenIssuer: 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 claim
    JwtTokenIssuer signals an incorrect iss claim
    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 signals a required aud claim is missing
    JwtPayloadRequiresAud signals a required aud claim is missing
    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 signals the aud claim does not match
    JwtTokenAudience signals the aud claim does not match
    JwtTokenAudience
  • JwtTokenSignatureMismatched: Indicates a signature mismatch in the token.
    JwtTokenSignatureMismatched: Indicates a signature mismatch in the token.
    JwtTokenSignatureMismatched signals a signature mismatch
    JwtTokenSignatureMismatched signals a signature mismatch
    JwtTokenSignatureMismatched

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-256
    HS256: HMAC using SHA-256
    HS256 is HMAC using SHA-256
    HS256 is HMAC using SHA-256
    HS256
  • HS384: HMAC using SHA-384
    HS384: HMAC using SHA-384
    HS384 is HMAC using SHA-384
    HS384 is HMAC using SHA-384
    HS384
  • HS512: HMAC using SHA-512
    HS512: HMAC using SHA-512
    HS512 is HMAC using SHA-512
    HS512 is HMAC using SHA-512
    HS512
  • RS256: RSASSA-PKCS1-v1_5 using SHA-256
    RS256: RSASSA-PKCS1-v1_5 using SHA-256
    RS256 is RSASSA-PKCS1-v1_5 using SHA-256
    RS256 is RSASSA-PKCS1-v1_5 using SHA-256
    RS256
  • RS384: RSASSA-PKCS1-v1_5 using SHA-384
    RS384: RSASSA-PKCS1-v1_5 using SHA-384
    RS384 is RSASSA-PKCS1-v1_5 using SHA-384
    RS384 is RSASSA-PKCS1-v1_5 using SHA-384
    RS384
  • RS512: RSASSA-PKCS1-v1_5 using SHA-512
    RS512: RSASSA-PKCS1-v1_5 using SHA-512
    RS512 is RSASSA-PKCS1-v1_5 using SHA-512
    RS512 is RSASSA-PKCS1-v1_5 using SHA-512
    RS512
  • PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256
    PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256
    PS256 is RSASSA-PSS using SHA-256 and MGF1
    PS256 is RSASSA-PSS using SHA-256 and MGF1
    PS256
  • PS384: RSASSA-PSS using SHA-386 and MGF1 with SHA-386
    PS384: RSASSA-PSS using SHA-386 and MGF1 with SHA-386
    PS384 is RSASSA-PSS using SHA-384 and MGF1
    PS384 is RSASSA-PSS using SHA-384 and MGF1
    PS384
  • PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512
    PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512
    PS512 is RSASSA-PSS using SHA-512 and MGF1
    PS512 is RSASSA-PSS using SHA-512 and MGF1
    PS512
  • ES256: ECDSA using P-256 and SHA-256
    ES256: ECDSA using P-256 and SHA-256
    ES256 is ECDSA using P-256 and SHA-256
    ES256 is ECDSA using P-256 and SHA-256
    ES256
  • ES384: ECDSA using P-384 and SHA-384
    ES384: ECDSA using P-384 and SHA-384
    ES384 is ECDSA using P-384 and SHA-384
    ES384 is ECDSA using P-384 and SHA-384
    ES384
  • ES512: ECDSA using P-521 and SHA-512
    ES512: ECDSA using P-521 and SHA-512
    ES512 is ECDSA using P-521 and SHA-512
    ES512 is ECDSA using P-521 and SHA-512
    ES512
  • EdDSA: EdDSA using Ed25519
    EdDSA: EdDSA using Ed25519
    EdDSA is EdDSA using Ed25519
    EdDSA is EdDSA using Ed25519
    EdDSA