---
title: "Authentication Middleware"
description: "Authentication middleware in Hono serves as the primary security layer for guarding routes, ensuring that incoming HTTP requests carry valid credentials before reaching the business logic. By lever..."
last_updated: "2026-07-02T09:13:47.358502+00:00"
canonical_url: "https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/middleware-ecosystem/authentication-middleware"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [src/utils/jwt/jwt.ts](https://github.com/blade47/hono/blob/main/src/utils/jwt/jwt.ts)
- [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/main/src/middleware/secure-headers/secure-headers.ts)
- [package.json](https://github.com/blade47/hono/blob/main/package.json)
- [src/middleware/jwk/jwk.ts](https://github.com/blade47/hono/blob/main/src/middleware/jwk/jwk.ts)
- [src/middleware/jwt/jwt.ts](https://github.com/blade47/hono/blob/main/src/middleware/jwt/jwt.ts)
- [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/main/src/middleware/bearer-auth/index.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/main/src/hono-base.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/main/src/types.ts)
</details>

Authentication middleware in Hono serves as the primary security layer for guarding routes, ensuring that incoming HTTP requests carry valid credentials before reaching the business logic. By leveraging standard Web Crypto APIs and JWT specifications, these components provide a robust, non-blocking flow that integrates seamlessly into the Hono middleware pipeline.

The architecture is designed to handle multiple common authentication patterns, including standard Bearer tokens, JSON Web Key (JWK) rotation through remote URI fetching, and static token validation. Because Hono is built on Web Standards, the middleware is platform-agnostic, running effectively across Cloudflare Workers, Node.js, Bun, and Deno, relying solely on the standard `crypto.subtle` API for cryptographic operations.

These components operate by inspecting headers or cookies, verifying claims against provided secrets or public keys, and either passing the request forward via `next()` or terminating execution early with an `HTTPException`. This ensures that downstream handlers only process requests that have satisfied the authentication invariant.

## JSON Web Token (JWT) Verification

The core of Hono's token-based authentication lies in the `Jwt` utility and its corresponding middleware. It provides high-level abstractions for signing and verifying tokens, adhering to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519).

The `verify` function is the primary mechanism for token validation. It performs an ordered check:
1. **Header/Payload structure**: It ensures the token has exactly three parts (split by `.`).
2. **Algorithm enforcement**: It validates that the token's `alg` matches the expected algorithm, preventing "alg: none" or algorithm confusion attacks.
3. **Claim validation**: It checks `nbf` (Not Before), `exp` (Expiration), and `iat` (Issued At) against the current time.
4. **Signature verification**: It uses the Web Crypto `verifying` function to ensure the signature matches the signed header and payload.

> [!CAUTION]
> When using `verifyWithJwks`, the implementation enforces an explicit exclusion of symmetric algorithms (HS256/384/512) to prevent algorithm confusion attacks where a client might attempt to use a public key as a HMAC secret.

Sources: [src/utils/jwt/jwt.ts:96-188](https://github.com/blade47/hono/blob/main/src/utils/jwt/jwt.ts#L96-L188)

## JWK Auth Middleware

The `jwk` middleware extends the JWT functionality by supporting dynamic public key rotation, commonly required in OIDC-compliant identity providers.

When `jwks_uri` is provided, the middleware dynamically fetches the keyset. The mechanism involves:
1. Extracting the `kid` (Key ID) from the JWT header.
2. If `jwks_uri` is present, performing a `fetch` to retrieve the JSON Web Key Set.
3. Matching the `kid` from the token against the retrieved `keys` array.
4. If a match is found, executing the standard signature verification process.

```typescript
// Example: Using JWK middleware with a dynamic URI
app.use("/auth/*", jwk({
  jwks_uri: (c) => `https://${c.env.authServer}/.well-known/jwks.json`,
  alg: ['RS256']
}))
```
Sources: [src/middleware/jwk/jwk.ts:48-168](https://github.com/blade47/hono/blob/main/src/middleware/jwk/jwk.ts#L48-L168)

## Bearer Auth Middleware

The `bearerAuth` middleware provides a simplified, non-JWT-specific token validation mechanism. It is ideal for API key-based authentication where the token itself does not need a structured payload.

It supports two validation strategies:
1. **Static Tokens**: Validates against a string or array of strings.
2. **Dynamic Validation**: Uses a `verifyToken` function for custom logic (e.g., database lookup).

The security-critical component is the `timingSafeEqual` function, which prevents timing attacks by performing constant-time string comparison.

```typescript
// Example: Using bearer authentication with a static token
app.use('/api/*', bearerAuth({ token: 'my-secret-token' }))
```
Sources: [src/middleware/bearer-auth/index.ts:104-221](https://github.com/blade47/hono/blob/main/src/middleware/bearer-auth/index.ts#L104-L221)

## IP Restriction Middleware

The `ipRestriction` middleware provides infrastructure-level access control by inspecting the remote IP address of incoming requests.

**Mechanism:**
1. **Matching**: It accepts static IPs or CIDR notation (e.g., `10.0.0.0/8`).
2. **Registration**: The `buildMatcher` function compiles rules into `Set` structures for constant-time lookup and binary masks for CIDR ranges.
3. **Execution**: The IP is parsed and compared against the compiled rules. If a `denyList` rule matches, access is rejected. If an `allowList` is provided, the request must match at least one rule to proceed.

> [!NOTE]
> When `allowList` is provided, the middleware behaves as a whitelist-only filter. If the list is empty, it falls back to permissive behavior unless `denyList` rules trigger a block.

Sources: [src/middleware/ip-restriction/index.ts:51-167](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts#L51-L167)

## Security Design Decisions

| Design Choice | Benefit | Cost |
| :--- | :--- | :--- |
| **Web Crypto API** | Platform-independent, secure native implementation | Less granular control over low-level crypto primitives |
| **Middleware Chaining** | Composable, allows layering (e.g., IP + JWT) | Higher stack depth for complex request pipelines |
| **Compile-time Matching** | Efficient IP restriction for high-traffic apps | Overhead during middleware initialization phase |
| **Typed Responses** | Improved type safety for error handling | Increased boilerplate for custom error responses |

Sources: [src/utils/jwt/jwt.ts](https://github.com/blade47/hono/blob/main/src/utils/jwt/jwt.ts), [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts)

## Request Flow Visualization

This diagram traces the standard authentication middleware sequence.

```mermaid
flowchart TD
    Req["Incoming Request"] --> Auth["Auth Middleware"]
    Auth --> Valid{Is Token/IP<br>Valid?}
    Valid -- No --> Err["401 Unauthorized<br>or 403 Forbidden"]
    Valid -- Yes --> Ctx["Set Auth Info<br>in c.jwtPayload"]
    Ctx --> Next["await next()"]
    Next --> Biz["Business Logic"]
```
Sources: [src/middleware/jwt/jwt.ts:76-158](https://github.com/blade47/hono/blob/main/src/middleware/jwt/jwt.ts#L76-L158), [src/middleware/ip-restriction/index.ts:238-279](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts#L238-L279)

## Related

- [Security Headers](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/middleware-ecosystem/security-headers)
- [Cryptography and JWT](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/system-utilities/cryptography-and-jwt)


## Sitemap

See the full [sitemap](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/llms.txt) for all pages in this wiki.
