Skip to content
12 min read

Authentication that fails safely

A platform in front of Forgejo has to answer one question thousands of times a minute: is this person still allowed to do this? The answers that go wrong are rarely cryptographic. They are a token that outlives the account it was issued for, a security key that will not register because of a hostname, or a sign-in partner that quietly accepts the wrong redirect.

This runbook covers the shape we recommend and the failures we have met or designed against. It is generic: the names are ours to choose, and yours to change. For the sign-out half, see Sign-out that really ends the session.

Note

These pages describe patterns, not a configuration to copy. Lifetimes, limits and hashing parameters are deployment decisions. Treat the values you see here as the kind of number to choose, and measure your own.

Short access, rotating refresh

Use two tokens with different jobs.

TokenLifetimeJobWhere it is checked
Access tokenShort, an hour or lessAuthorises one request.Signature, expiry, and a fresh look at the account.
Refresh tokenLonger, about a dayGets a new pair, nothing else.A server-side record, so it can be revoked.

Sign both with an asymmetric key, so any service can verify them and only one can mint them. Give the refresh token a different type from the access token so one can never be presented as the other.

Rotate on every use. A refresh mints a new access token and a new refresh token and revokes the old one in the same atomic step. On detected reuse of a spent refresh token, reject the request and atomically revoke its entire refresh family, including the current successor, so a thief who refreshed first cannot keep renewing access. Record the replay in the audit log. Serialize client renewals and let concurrent callers reuse the winning result, as described in the sign-out runbook, so legitimate concurrent requests do not trigger family revocation.

Revoke without a session store

A stateless access token cannot be deleted, so make it fail a check instead. Put a token version in the token and keep the current version on the account. On each request, load the account and reject the token if the account is disabled or the versions differ.

Bump the version, and revoke every refresh token for the account, on:

  • a password change,
  • a role change,
  • disabling the account.

That makes revocation immediate at the cost of one account lookup per request. If the lookup is too costly, you have not removed the check, you have moved the window: a cache of N seconds means a disabled account keeps working for N seconds. Decide that number on purpose.

Treat the role in the token as a hint for the client. Authorise on the role you just loaded. An unknown role string must fall back to the least privileged role, never to an error that skips the check.

Where the token lives is a trade

PlaceProtects againstExposed to
Authorization header, token kept by the page (for example in local storage)Cross-site request forgery, because the browser does not send it by itself.Script injection, because any script on the page can read it.
Cookie marked HttpOnly, Secure, SameSiteScript injection reading it.Forgery, so it needs a token or origin check on every state change.

Neither is free. If you choose the header, spend the effort on content-security policy and dependencies, and keep the admin surface server-side so its key never reaches a browser. If you choose cookies, see the forgery checks in the sign-out runbook.

Lock cross-origin access to an explicit list in production. Allow-any-origin is a development convenience, and a development flag that relaxes it should also restrict the service to loopback, so that it cannot be left on by accident on a reachable host.

Rate limits that survive reality

Limit sign-in, registration and refresh by client address, with a stricter window on sign-in. Return 429 with a Retry-After. Then check the three ways it fails:

  • In-memory limits are per process. Run three instances and the real limit is three times what you wrote. They also reset on every restart, which is exactly when an attacker would like it to.
  • The address is only as good as your proxy. Read a forwarded header only from a proxy you trust. Anywhere else the caller picks their own address and the limit disappears.
  • A limit on the wrong key locks out the wrong people. Everyone behind one office network shares an address.

Passwords and the audit log

Hash passwords with a memory-hard function and a per-account salt, and tune the cost on production hardware so a login is not the slowest thing you do.

Log authentication events with a stable prefix: sign-in success and failure, lockout, password change, role change, account disabled, token version bumped. Never log a password, a token or an email address. Do not record an account id for a sign-in that named an unknown email, or the log answers “does this account exist?“.

Security keys (WebAuthn)

Security keys and platform authenticators are the strongest second factor you can offer, and also the one with the most opaque failures. The rules that matter:

  • The relying-party origin must equal the origin in the address bar, exactly. localhost and 127.0.0.1 are different origins. So are http and https, and with and without a port. Set one value and use one hostname everywhere.
  • It needs a secure context. HTTPS in production; localhost is the only exception.
  • Restart after changing the origin. The value is read at startup.
  • Pending challenges are held in memory with a short lifetime. A restart, or a second instance that did not issue the challenge, fails the sign-in that was in flight. Pin the second step to the instance that issued the first, or store the challenge where every instance can read it.
  • Say when the feature is off. When the origin is unset or rejected at startup, listing credentials should still answer, with an explicit “not available”, so the interface hides enrolment. Endpoints that act on a key should fail with 503, not pretend.

Registration flow, for orientation: the user signs in with a password, asks to add a key, the server returns a registration id and creation options, the browser asks the authenticator, and the server stores the credential. Sign-in with a key reverses it: password first, then, if the account has keys, a challenge id and request options, the browser’s answer, and only then the session. An account that has a key requires it from that moment.

Common reports, in order of how often they are the cause:

  1. The origin does not match. Open the exact configured URL.
  2. The service was not restarted after the origin changed.
  3. The key is not in the mode the site asks for, or needs a touch it is not getting.
  4. A browser with a known issue with a particular kind of USB key. Register the key in a browser that works, then sign in anywhere that supports it.

Offer a way back in. An account with one key and no other recovery is one lost key from a support ticket and an identity check. Recovery codes or a second registered key are the cheapest fix, and removing the last key should say what it does.

Single sign-on: your platform as the identity provider

When other tools (a forum, an admin console, mobile apps) should trust the same accounts, make the platform an OpenID Connect provider. The asymmetry is the point: the provider is trusted by its clients, and trusts none of them.

What to publish. A discovery document, a key set with a key id, an authorise endpoint, a token endpoint, a userinfo endpoint and an end-session endpoint.

What to insist on.

  • Authorization code flow with PKCE, challenge method S256 only. Public clients, such as mobile apps, then need no shipped secret. Do not offer plain.
  • Exact redirect matching. The redirect URI must equal a registered value character for character, trailing slash included. Prefix and wildcard matching is how a code is delivered to an attacker.
  • A client registry where each client has its own redirect and post-logout addresses, and confidential clients have a secret you generated.
  • Signed identity tokens carrying issuer, subject, audience, expiry, the time the user actually authenticated, and the authorised party.

What every client must validate, and what you should test, not assume: the signature against the published keys (matching the key id), the issuer, the audience, and expiry. A client that skips the audience check accepts tokens minted for someone else.

Role mapping is optional and worth deciding deliberately. Passing the platform role as a claim lets an administrator be an administrator everywhere, and also lets a compromised provider promote itself everywhere. Map only the roles you mean to.

Prove the first round trip

Do one real browser flow before launch: open the client, choose to sign in, land on the provider, authenticate, return with a code, exchange it, and see the account created. Then test the part people skip:

  • sign out of the client and check the provider session is gone, as the sign-out runbook describes,
  • sign in again and see whether single sign-on persists while the provider session is alive,
  • revoke the provider session and confirm the next sign-in at the client demands fresh authentication. That proves the provider side. It does not end a client session that already exists: after the code exchange a client usually holds its own cookie, which stays valid until it expires unless you add back-channel logout or an ongoing revocation check. So also send a request from an already signed-in client after the revocation, record what happens, and decide whether that window is acceptable. Check that a session on another device survives, or you have revoked more than you meant to.

End-session needs care, because it pulls two ways. A provider session that is not cleared leaves people unable to stay signed out of a client: the next authorise request quietly issues a new code. Clearing it for any request that arrives, though, lets another site send the browser to the end-session address and sign the user out without their consent, and exact redirect matching protects the destination, not the logout. Resolve it with a rule:

  • Clear the provider cookie automatically only when the request is correlated with the browser’s current provider session. The identity-token hint must verify against your keys, name a registered client as audience, carry your issuer, and have a subject equal to the subject of the session being cleared. A valid signature only shows who a token was issued to. Without the subject match, an attacker can take a token from their own sign-in and put it in a link to someone else.
  • Otherwise ask first. For no hint, an invalid hint, a client and hint that disagree, or a subject that does not match, show a “sign out?” page. Its button is a POST to the provider itself, protected by a token tied to that page, and only the POST clears the cookie.
  • The hint’s expiry can be ignored, since you are matching a subject, not granting access. It authorises nothing else.
  • Only after clearing, send the browser back, and only to a post-logout address registered for that client, matched exactly, or you have built an open redirect.

Keep two kinds of route apart. The client’s own local sign-out is a state-changing route, and the cross-site checks in the sign-out runbook apply to it. The provider’s end-session endpoint is different: it must accept the browser’s top-level navigation (a GET, from another origin) or legitimate sign-out never reaches it, which is the failure this section started with. Protect that entry point with the correlation and confirmation rules above, not with a POST-only or same-origin rule.

Failure modes

What you seeUsual causeWhat to do
A disabled user keeps working for a whileA cache on the account lookup, or the token version was not bumped.Bump the version, revoke refresh tokens, and check the cache lifetime.
Refresh works twice with the same tokenRotation did not revoke the old one.Revoke on use; on detected reuse, reject the request, atomically revoke the entire refresh family including its current successor, and log and alert on the replay. Verify that the successor also fails.
Brute-force limit seems ignoredSeveral instances, a restart, or a spoofable address header.Move the counter to shared storage and trust only your proxy.
Everyone behind one network is locked outThe limit is keyed on a shared address.Add an account-based limit and widen the address one carefully.
Security key never respondsOrigin mismatch, no restart, or the wrong key mode.Use the exact configured URL and restart after changes.
Sign-in with a key fails after a deployThe challenge was in memory and the instance restarted.Keep the challenge somewhere durable, or tell users to try again.
A client returns “redirect mismatch”The registered value differs by a slash, scheme or port.Register the exact URL the client sends.
A user cannot stay signed out of a clientThe provider session cookie was never cleared.Route sign-out through end-session.
A client accepts a token for another clientIt does not validate the audience.Fix the client, and add a test that sends a token for a different audience.

Verify it is healthy

  • Disable a test account and confirm its access token fails on the next request.
  • Change its password and confirm every refresh token for it is rejected.
  • Exchange a refresh token and retain its successor, then replay the old token. Confirm the replay fails and is logged, then confirm the successor also fails because the entire refresh family was revoked.
  • Send a login burst from one address and from two, behind your real proxy, and confirm the limit you intended is the limit you got.
  • Register a key, restart the service, and sign in with it.
  • Send an authorise request with a near-miss redirect and confirm it is refused.
  • Validate an identity token with a deliberately wrong audience and confirm the client rejects it.
  • Rotate the signing key in a staging environment and watch every client pick up the new key from the key set, by key id, without a deploy.
Contributors
  • Stephen Way