---
title: "Authentication"
description: "Session cookies and JWT bearer tokens: how to implement both, when each fits, and the difference between 401 and 403."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

Two patterns cover almost every API. Session cookies pair a random ID in a
signed cookie with a server-side session record; they are simpler than JWTs and
the right default when the API serves your own browser app. Bearer tokens
(JWTs) are verified by signature alone, which lets any service holding the
public key authenticate requests without shared state.

## Choosing between them

| Concern       | Session cookies                                  | Bearer tokens (JWT)                              |
| ------------- | ------------------------------------------------ | ------------------------------------------------ |
| Revocation    | Delete the session row; takes effect immediately | Valid until `exp` unless you maintain a denylist |
| Server state  | Session store shared by every instance           | None beyond the verification key                 |
| Clients       | Browsers; the cookie jar handles transport       | Any HTTP client: mobile, CLIs, other services    |
| Cross-service | Every verifier needs the session store           | Any service with the public key verifies locally |
| Moving parts  | One table, one cookie                            | Key distribution, rotation, refresh flow         |

First-party browser app: use sessions. Public API, mobile clients, or
service-to-service calls: use bearer tokens. Serving both from one API is
common: sessions for the web app, tokens for everything else.

## Session cookies

Login verifies credentials, inserts a session row, and sets a cookie holding
the session ID. The browser attaches the cookie to every subsequent request.
Logout deletes the row, and the cookie becomes useless even if it lingers in
the browser.

```http
HTTP/1.1 204 No Content
Set-Cookie: __Host-session=Zj3kQ9wXaTr5bYv2Nc8pDw.tGx9vQ3mKfR7sLwYhB1zUuE4; Path=/; Max-Age=604800; Secure; HttpOnly; SameSite=Lax
```

### Cookie attributes

Every attribute in that `Set-Cookie` line is load-bearing:

| Attribute        | What it does                                                                                                          |
| ---------------- | --------------------------------------------------------------------------------------------------------------------- |
| `__Host-` prefix | The browser rejects it unless set over HTTPS with `Path=/` and no `Domain`; a compromised subdomain can't override it |
| `HttpOnly`       | JavaScript can't read it, so XSS can't exfiltrate the session                                                         |
| `Secure`         | Never sent over plain HTTP                                                                                            |
| `SameSite=Lax`   | Not sent on cross-site subrequests or form POSTs; blocks most CSRF                                                    |
| `Max-Age`        | Client-side lifetime; pair it with `expires_at` server-side                                                           |

:::caution
`SameSite=Lax` still sends the cookie on top-level navigations, so a cross-site link triggers a
GET with the session attached. Keep state changes out of GET handlers. If you must accept
cross-site POSTs, add CSRF tokens; `SameSite` alone does not cover that case.
:::

### Sign the cookie

The session ID is already unguessable (128 random bits), so the signature is
not what prevents forgery. It lets the server reject tampered or fabricated
cookies with one HMAC comparison instead of a session-store lookup, and it
guarantees the value round-tripped unmodified. Frameworks with cookie helpers
(Hono, axum-extra, Rails) sign by default; match that when rolling your own.

The format is `value.signature`, where the signature is HMAC-SHA256 over the
value, base64url-encoded. Use a single 64-byte random key from your secrets
manager; rotating it invalidates every outstanding cookie, which doubles as a
global logout.

### Session store

```sql
CREATE TABLE sessions (
  id         TEXT        NOT NULL PRIMARY KEY, -- 128-bit random, base64url
  user_id    BIGINT      NOT NULL REFERENCES users (id),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  expires_at TIMESTAMPTZ NOT NULL
);
```

Lookups filter on `expires_at > now()` so an expired session behaves exactly
like a deleted one. Logout is a `DELETE`; a periodic job clears expired rows:

```sql
-- logout
DELETE FROM sessions WHERE id = $1;

-- nightly cleanup
DELETE FROM sessions WHERE expires_at < now();
```

### Implementation

### Go

Signing and verification with the standard library:

```go
var cookieKey = []byte(os.Getenv("COOKIE_KEY")) // 64 random bytes

func sign(value string) string {
    mac := hmac.New(sha256.New, cookieKey)
    mac.Write([]byte(value))
    return value + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}

func verify(signed string) (string, bool) {
    value, sig, ok := strings.Cut(signed, ".")
    if !ok {
        return "", false
    }
    mac := hmac.New(sha256.New, cookieKey)
    mac.Write([]byte(value))
    got, err := base64.RawURLEncoding.DecodeString(sig)
    return value, err == nil && hmac.Equal(got, mac.Sum(nil))
}
```

Login creates the session row and sets the signed cookie:

```go
func handleLogin(store *SessionStore) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // ... verify credentials, yielding userID ...

        buf := make([]byte, 16)
        if _, err := rand.Read(buf); err != nil {
            http.Error(w, "internal error", http.StatusInternalServerError)
            return
        }
        sessionID := base64.RawURLEncoding.EncodeToString(buf)

        if err := store.Create(r.Context(), sessionID, userID, 7*24*time.Hour); err != nil {
            http.Error(w, "internal error", http.StatusInternalServerError)
            return
        }

        http.SetCookie(w, &http.Cookie{
            Name:     "__Host-session",
            Value:    sign(sessionID),
            Path:     "/",
            MaxAge:   7 * 24 * 3600,
            Secure:   true,
            HttpOnly: true,
            SameSite: http.SameSiteLaxMode,
        })
        w.WriteHeader(http.StatusNoContent)
    }
}
```

Middleware verifies the signature before touching the store:

```go
func requireSession(store *SessionStore, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        c, err := r.Cookie("__Host-session")
        if err != nil {
            http.Error(w, "authentication required", http.StatusUnauthorized)
            return
        }
        id, ok := verify(c.Value)
        if !ok {
            http.Error(w, "authentication required", http.StatusUnauthorized)
            return
        }
        sess, err := store.Get(r.Context(), id) // filters expires_at > now()
        if errors.Is(err, ErrNoSession) {
            http.Error(w, "authentication required", http.StatusUnauthorized)
            return
        }
        if err != nil {
            http.Error(w, "internal error", http.StatusInternalServerError)
            return
        }
        next.ServeHTTP(w, r.WithContext(withSession(r.Context(), sess)))
    })
}
```

### Rust (axum)

`axum-extra`'s `SignedCookieJar` signs on write and rejects bad signatures on
read:

```toml
# Cargo.toml
axum-extra = { version = "0.10", features = ["cookie-signed"] }
time = "0.3"
```

The jar pulls the signing key from router state through `FromRef`:

```rust
use axum::extract::FromRef;
use axum_extra::extract::cookie::{Cookie, Key, SameSite, SignedCookieJar};

#[derive(Clone)]
struct AppState {
    key: Key,
    // db pool, etc.
}

impl FromRef<AppState> for Key {
    fn from_ref(state: &AppState) -> Key {
        state.key.clone()
    }
}

fn app() -> Router {
    let state = AppState {
        key: Key::from(&load_cookie_key()), // 64 random bytes; panics if shorter
    };
    Router::new()
        .route("/v1/login", post(login))
        .route("/v1/me", get(me))
        .with_state(state)
}
```

```rust
async fn login(jar: SignedCookieJar) -> Result<(SignedCookieJar, StatusCode), StatusCode> {
    // ... verify credentials, insert the session row ...
    let session_id = new_session_id(); // 128-bit random, base64url

    let cookie = Cookie::build(("__Host-session", session_id))
        .path("/")
        .max_age(time::Duration::days(7))
        .secure(true)
        .http_only(true)
        .same_site(SameSite::Lax);

    Ok((jar.add(cookie), StatusCode::NO_CONTENT))
}

async fn me(jar: SignedCookieJar) -> Result<Json<User>, StatusCode> {
    // get() returns None for a missing cookie or an invalid signature.
    let Some(cookie) = jar.get("__Host-session") else {
        return Err(StatusCode::UNAUTHORIZED);
    };
    let session_id = cookie.value();
    // ... look up the session row, filtering expires_at > now() ...
}
```

### TypeScript (Hono)

Hono ships signed cookie helpers; `prefix: "host"` names the cookie
`__Host-session`:

```ts
import { Hono } from "hono";
import { getSignedCookie, setSignedCookie } from "hono/cookie";

const app = new Hono();
const secret = process.env.COOKIE_KEY!; // 64 random bytes, hex

app.post("/v1/login", async (c) => {
  // ... verify credentials, insert the session row ...
  await setSignedCookie(c, "session", sessionId, secret, {
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
    secure: true,
    httpOnly: true,
    sameSite: "Lax",
    prefix: "host",
  });
  return c.body(null, 204);
});

app.get("/v1/me", async (c) => {
  // Returns false for an invalid signature, undefined for a missing cookie.
  const sessionId = await getSignedCookie(c, secret, "session", "host");
  if (!sessionId) {
    return c.json(
      { error: { code: "AUTHENTICATION_REQUIRED", message: "Sign in to continue." } },
      401,
    );
  }
  // ... look up the session row, filtering expires_at > now() ...
});
```

## Bearer tokens (JWT)

The client sends the token in the `Authorization` header on every request. The
token carries enough signed information for the server to decide who is
calling and what they may do, with no session store involved.

### The Authorization header

```http
GET /v1/users HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
```

`Bearer` is the scheme. Everything after the space is the token. Never accept
tokens in query strings (`?token=...`) or request bodies: URLs leak into server
logs, browser history, and Referer headers. The `Authorization` header stays
out of all three.

### JWT structure

A JWT is three base64url-encoded segments separated by dots: `header.payload.signature`.
The payload (claims) is the part your API cares about:

```json
{
  "sub": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "iss": "https://auth.example.com",
  "aud": "https://api.example.com",
  "iat": 1701437445,
  "exp": 1701441045,
  "scope": "read:users write:orders"
}
```

**Claims to include:**

| Claim   | Purpose                                                         |
| ------- | --------------------------------------------------------------- |
| `sub`   | The user or service identity (your UUID)                        |
| `iss`   | Who issued the token; lets you reject tokens from other issuers |
| `aud`   | Who the token is intended for; your API's base URL              |
| `iat`   | Issued-at time (Unix seconds)                                   |
| `exp`   | Expiry time (Unix seconds); always set this                     |
| `scope` | Space-separated list of permissions                             |

The `sub` value is your external identifier for the user or service. See
[Identities](https://codex.mirio.dev/databases/table-design/identities/) for the choice between UUIDs and
prefixed IDs, and why the external identifier differs from the database primary key.

Keep the payload small. Tokens are sent on every request; large payloads add
latency and make headers easier to exceed. Store profile data server-side and
look it up from `sub` if you need it.

**Algorithm:** Use `RS256` (RSA + SHA-256) or `ES256` (ECDSA + SHA-256) for
tokens issued by an authorization server, so the signing key stays private and
the public key can be distributed to any service that needs to verify. Avoid
`HS256` in multi-service environments: it requires sharing the secret with every
verifier.

### Token lifetimes

Short-lived access tokens limit the damage when a token leaks:

| Token type    | Typical lifetime | Notes                                             |
| ------------- | ---------------- | ------------------------------------------------- |
| Access token  | 15 min – 1 hour  | Sent with every request; rotate frequently        |
| Refresh token | 7 – 30 days      | Used only to get new access tokens; rotate on use |
| API key       | Indefinite       | For machine-to-machine; revocable, not expiring   |

When an access token expires, the client exchanges the refresh token for a new
pair. Rotate the refresh token on each use (refresh token rotation); a used
refresh token is evidence of replay if it appears again.

### Token refresh flow

```http
POST /v1/auth/token HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "grant_type": "refresh_token",
  "refresh_token": "8xLOxBtZp8"
}
```

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "9yMPyCuAq9"
}
```

## 401 vs 403

These are distinct errors and must not be conflated:

| Status             | Meaning                          | When to return                                                  |
| ------------------ | -------------------------------- | --------------------------------------------------------------- |
| `401 Unauthorized` | Not authenticated                | Missing token, expired token, invalid signature, wrong audience |
| `403 Forbidden`    | Authenticated but not authorized | Valid token, but the caller lacks the required scope or role    |

A `401` tells the client to re-authenticate. A `403` tells the client their
identity is known but the answer is still no: re-authenticating won't help.
Returning `403` for missing tokens leaks less information but confuses clients
more than it protects; use `401` when the problem is identity.

```http
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api.example.com", error="invalid_token", error_description="Token has expired"
Content-Type: application/json

{
  "error": {
    "code": "TOKEN_EXPIRED",
    "message": "The access token has expired. Obtain a new token and retry."
  }
}
```

Include the `WWW-Authenticate` header on `401` responses to bearer-token
requests: it's the standard signal that bearer authentication is required and
tells the client what went wrong. Cookie sessions have no registered
authentication scheme, so a `401` with an error body is the whole response;
missing, invalid, and expired sessions all look the same to the client.

Source: https://codex.mirio.dev/web/rest-apis/authentication/index.mdx
