Orientation Arc
Routing Algorithms
Rendering and JSX
Runtime Adapters
Middleware Ecosystem
Developer Helpers
System Utilities
The following files were used as context for generating this wiki page:
Cryptography and JWT form a critical security layer within the Hono framework, providing robust mechanisms for identity verification, data integrity, and secure transport state management. The architecture decouples cryptographic primitives from high-level authentication middleware, allowing developers to sign, verify, and decode JSON Web Tokens (JWT) while leveraging the underlying Web Crypto API. This approach ensures Hono remains compliant with modern web standards while remaining runtime-agnostic.
The subsystem addresses common security challenges such as algorithm confusion attacks, token expiration, and unauthorized access. By providing dedicated middleware like jwt() and jwk(), Hono simplifies the implementation of stateless authentication. These components maintain a clean separation between the cryptographic operations—handled in jws.ts—and the routing/request handling logic, ensuring that sensitive token validation logic remains centralized and testable.
Integration with adjacent components is seamless, particularly regarding request context and headers. The secure-headers middleware works in tandem with these security modules to prevent vulnerabilities like CSRF or content-injection, while the cookie helpers offer cryptographically signed cookies to extend the lifecycle of authentication states. By prioritizing standard-compliant implementations of RFC 7515 (JWS) and RFC 7519 (JWT), this component ensures secure interoperability with external identity providers and authentication services.
The core cryptographic operations are abstracted through jws.ts, which leverages crypto.subtle to perform signing and verification. Rather than implementing proprietary crypto, Hono maps high-level algorithms (like HS256, RS256, or ES256) to the corresponding SubtleCrypto parameters. The getKeyAlgorithm function acts as a central registry for this mapping, converting a SignatureAlgorithm string into the required KeyAlgorithm structure.
Sources: src/utils/jwt/jws.ts:29-48, src/utils/jwt/jws.ts:122-224
The Jwt.verify function serves as the primary engine for token authentication. It performs a multi-stage validation process: token structure verification, header integrity, expiration/time-based checks, and final signature validation.
Important
The verify function strictly enforces that alg (algorithm) is provided. This prevents "None" algorithm attacks where an attacker replaces the algorithm header to bypass signature checks.
The flow ensures that security invariants are maintained before the signature is ever checked:
.. Expect exactly 3 parts.alg in header.nbf (Not Before), exp (Expiration), and iat (Issued At) against current server time.verifying() to compare the signature of the header.payload string against the provided public key.Sources: src/utils/jwt/jwt.ts:96-188
The verifyWithJwks function provides a more advanced security model by fetching public keys from a URI or using a provided key set. It specifically hardens the system against Algorithm Confusion Attacks.
Warning
The system explicitly rejects symmetric algorithms (HS256, HS384, HS512) during JWK verification. This prevents an attacker from supplying an asymmetric public key as a symmetric "secret" to force the server into using a weak signature validation logic.
Sources: src/utils/jwt/jwt.ts:197-262
The jwt and jwk middleware wrap the core utilities to provide standard Hono middleware integration. They extract tokens from either the Authorization header (default: Bearer) or from cookie-based storage.
// Example: Basic JWT implementation
import { Hono } from 'hono'
import { jwt } from 'hono/jwt'
const app = new Hono()
app.use(
'/auth/*',
jwt({
secret: 'super-secret-key',
alg: 'HS256',
})
)
app.get('/auth/page', (c) => {
const payload = c.get('jwtPayload')
return c.text(`Authorized, user: ${payload.sub}`)
})The middleware provides an unauthorizedResponse helper that standardizes the WWW-Authenticate header, ensuring clients receive specific error and error_description fields when verification fails.
Sources: src/middleware/jwt/jwt.ts:53-158, src/middleware/jwk/jwk.ts:48-168
Hono provides mechanisms for managing signed cookies to preserve authentication state securely. The serializeSigned and parseSigned utilities use HMAC-SHA256 signatures to ensure cookie values cannot be tampered with by the client.
The verifySignature utility uses crypto.subtle.verify to check the HMAC, ensuring the integrity of the cookie data before it is made available to the application.
Sources: src/utils/cookie.ts:39-66, src/utils/cookie.ts:140-165
The csrf middleware complements JWT/Cookie-based auth by validating the origin of requests. It verifies that the request origin and/or Sec-Fetch-Site header correspond to a trusted value.
Tip
Always use a combination of secure cookies (via serializeSigned) and csrf() middleware to create a layered defense-in-depth strategy for stateful web apps.
The logic follows a short-circuit evaluation:
GET or HEAD).Content-Type indicates it could have been triggered by a standard HTML form element.isAllowedOrigin handler or Sec-Fetch-Site. If both checks fail, the system returns a 403 Forbidden.Sources: src/middleware/csrf/index.ts:94-151