---
title: "Authentication and Security"
description: "Authentication and security are critical components of any web application. This library provides built-in middleware to handle standard authentication patterns and protect your application against..."
last_updated: "2026-07-02T09:15:05.219505+00:00"
canonical_url: "https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/guide/middleware/authentication-and-security"
---

Authentication and security are critical components of any web application. This library provides built-in middleware to handle standard authentication patterns and protect your application against common web vulnerabilities, including Cross-Site Request Forgery (CSRF) and Cross-Origin Resource Sharing (CORS) issues.

## Authentication Middleware

You can secure your routes using either Basic Auth or Bearer Token authentication.

### Basic Auth
Used for protecting routes using standard `username` and `password` credentials.

```typescript
import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'

const app = new Hono()

app.use(
  '/admin/*',
  basicAuth({
    username: 'admin',
    password: 'password123',
  })
)
```

### Bearer Auth
Used for token-based authentication, typically for API endpoints.

```typescript
import { Hono } from 'hono'
import { bearerAuth } from 'hono/bearer-auth'

const app = new Hono()

app.use('/api/*', bearerAuth({ token: 'my-secret-token' }))
```

## Security Middleware

These tools protect your application from malicious cross-origin requests.

### CORS (Cross-Origin Resource Sharing)
Allows you to control which domains are permitted to access your resources.

```typescript
import { Hono } from 'hono'
import { cors } from 'hono/cors'

const app = new Hono()

app.use('/api/*', cors({
  origin: 'https://example.com',
  allowMethods: ['GET', 'POST'],
}))
```

| Option | Description |
| :--- | :--- |
| `origin` | The domain(s) allowed to access the resource |
| `allowMethods` | Allowed HTTP verbs (e.g., GET, POST) |
| `credentials` | Whether to allow cookies across origins |
| `maxAge` | Cache duration for preflight requests |

### CSRF (Cross-Site Request Forgery)
Protects against attacks where a malicious site tricks a user's browser into performing unwanted actions on your application.

```typescript
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'

const app = new Hono()

// Default protection validates 'origin' and 'sec-fetch-site'
app.use('*', csrf())
```

> [!WARNING]
> CSRF protection is generally not required for `GET` or `HEAD` requests. The `csrf` middleware automatically skips these safe methods.

## Key Concepts

*   **Middleware:** Functions that run during the request-response lifecycle before reaching your final route handler.
*   **Context (`c`):** An object passed to your handlers containing request data, response helpers, and environment variables.
*   **Timing Safe Comparison:** When comparing secrets (like tokens), the middleware uses `timingSafeEqual`. This prevents "timing attacks" where an attacker guesses a secret by measuring how long the comparison takes.
*   **`WWW-Authenticate` Header:** Used by authentication middleware to inform the client which authentication scheme to use when a request is denied.

> [!IMPORTANT]
> If you are building an API, ensure you use `bearerAuth` for token validation and `cors` to manage allowed origins. For user-facing forms, `csrf` is highly recommended to ensure the requests originate from your own application.

## Related

- [Utility Middleware](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/guide/middleware/utility-middleware)


## Sitemap

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