Web & UI/Routing & Authentication
Routing & Authentication
Typed routes, Authorize mixins, 5xx error reporting, sessions, auth/seal tokens, OIDC, JWT, API keys, RBAC, and rate limiting.
On this page
- Router Basics
- Group Root Routes
- Typed Routes
- Authorization Enforcement & Embedded Mixins
- Embedded Authorize Mixins
- Error Reporting & Router Options
- Sessions & Cookies
- Password Hashing
- CSRF Protection
- Sealed AEAD Tokens (auth/seal)
- Signed URLs (auth/signedurl)
- OIDC, OAuth, JWT, API Keys, and RBAC
- OIDC (auth/oidc)
- OAuth 2.0 (auth/oauth)
- JWT (auth/jwt)
- API Keys (auth/apikey)
- Role-Based Access Control (auth/rbac)
- Rate Limiting
Fletch splits HTTP routing and authentication into standalone Go modules (github.com/fletchhq/fletch/router and github.com/fletchhq/fletch/auth plus its submodules). Every route handler can bind typed inputs, enforce authorization statically through fletch check, and report 5xx failures through a structured hook.
Router Basics
Create a router with router.New(opts...) or use the router attached to fletch.App. Both expose the same registration methods.
r := router.New()
r.Use(requestIDMiddleware)
r.Handle("GET", "/health", healthHandler, router.WithName("health"), router.WithKind("json"))
r.Mount("/metrics", metricsHandler)
admin := r.Group("/admin", auth.RequireUser)
admin.Handle("GET", "", adminIndexHandler, router.WithName("admin.index"))
admin.Handle("GET", "/users/{id}", adminUserHandler, router.WithName("admin.users.show"))
Named routes resolve back to paths with r.URL(name, pairs...):
href, err := r.URL("admin.users.show", "id", "42")
// "/admin/users/42"
| Method / Option | Purpose |
|---|---|
router.New(opts...) |
Creates a standalone router with optional configuration. |
Use(mw...) |
Appends middleware to the router or current group. |
Group(prefix, mw...) |
Creates a prefixed sub-router with scoped middleware. |
Handle(method, pattern, h, opts...) |
Registers a raw handler for an HTTP method and path pattern. |
Mount(prefix, h) |
Delegates all requests under prefix to an http.Handler. |
URL(name, pairs...) |
Builds a path for a named route using key-value parameter pairs. |
router.WithName(name) |
Assigns a stable name for reverse URL generation and inspection. |
router.WithKind(kind) |
Tags the route kind for metadata and introspection. |
Group Root Routes
Group("/admin") accepts both "" and "/" as root patterns without producing double slashes or mismatched paths. Internally, cleanPrefix trims any trailing / from the group prefix before joining prefix + pattern, so registering "" or "/" inside Group("/admin") matches /admin cleanly.
Typed Routes
Every typed helper takes the router, a route name (or ""), a pattern, and a handler of type func(*router.Ctx, *Input) (Out, error). Typed route helpers bind request parameters, query values, JSON bodies, or form payloads into a struct before your handler runs. Any typed input implements router.Input:
type Input interface {
Bind(c *router.Ctx) error
Authorize(ctx context.Context) error
}
| Helpers | Response Type |
|---|---|
GetJSON, PostJSON, PutJSON, PatchJSON, DeleteJSON |
JSON response encoded from the handler’s return value. |
GetText, PostText |
Plain-text response. |
GetHTML |
Raw HTML response. |
GetPage |
Rendered Crest page response. |
PostForm, PutForm, PatchForm, DeleteForm |
Form submissions; embed router.FormErrors to re-render the form on bind errors. |
type CreateProjectInput struct {
RequireMember
Name string `json:"name"`
}
func (in *CreateProjectInput) Bind(c *router.Ctx) error {
return router.BindStruct(c, in)
}
func registerRoutes(r *router.Router, svc *ProjectService) {
router.PostJSON(r, "projects.create", "/api/projects", func(c *router.Ctx, in *CreateProjectInput) (*Project, error) {
return svc.Create(c.Context(), in.Name)
})
}
For multipart forms, validation helpers, and file uploads, see Forms & Uploads.
Authorization Enforcement & Embedded Mixins
Fletch enforces authorization on every binding input during static analysis (fletch check) as well as at runtime.
Every input struct that binds request data must either implement Authorize(ctx context.Context) error or explicitly embed fletch.Public (an alias for router.Public). Leaving both out fails fletch check with diagnostic W0201.
Writing a stub Authorize method whose body unconditionally returns nil triggers warning W0207. Embed fletch.Public on intentionally open endpoints so public routes stay auditable in code review and static checks.
type ListPublicDocsInput struct {
fletch.Public
Page int
}
func (in *ListPublicDocsInput) Bind(c *router.Ctx) error {
in.Page = 1
if v, ok := c.Query("page"); ok {
n, err := strconv.Atoi(v)
if err != nil {
return &router.BindError{Field: "page", Msg: "must be a number"}
}
in.Page = n
}
return nil
}
Embedded Authorize Mixins
When multiple endpoints share the same authorization check, define a zero-sized mixin struct and embed it in your input types:
package policies
import (
"context"
"github.com/fletchhq/fletch/auth"
)
type RequireAdmin struct{}
func (RequireAdmin) Authorize(ctx context.Context) error {
subject, ok := auth.User(ctx)
if !ok {
return auth.ErrUnauthenticated
}
if !isAdmin(ctx, subject) {
return auth.ErrForbidden
}
return nil
}
auth.User(ctx) returns the signed-in subject set by the session middleware; isAdmin stands for your own role lookup (for example an auth/rbac policy).
Embed policies.RequireAdmin into inputs in the same package or across packages:
type DeleteUserInput struct {
policies.RequireAdmin
ID string
}
func (in *DeleteUserInput) Bind(c *router.Ctx) error {
in.ID = c.Param("id")
return nil
}
fletch check resolves promoted Authorize methods automatically and does not flag the mixin type itself for lacking a Bind method. If an input embeds two structs that both define Authorize, Go’s method promotion becomes ambiguous and fletch check fails with W0201.
Error Reporting & Router Options
Pass router options to fletch.App through fletch.WithRouterOptions(opts ...router.Option). Fletch applies these options after its defaults, so your overrides take precedence.
By default, any handler error that produces a 5xx response is logged via slog.ErrorContext with the message "fletch: handler error" and structured attributes status, request_id, error, method, and path. Client errors in the 4xx range never trigger the error reporter.
Attach a custom reporter (for Sentry, Honeybadger, or an internal telemetry sink) with router.WithErrorReporter(fn). Inside fn(ctx context.Context, err error), call router.ReportedStatus(ctx) to read the HTTP status code written to the client.
app := fletch.New(
fletch.WithRouterOptions(
router.WithErrorReporter(func(ctx context.Context, err error) {
status := router.ReportedStatus(ctx)
errTracker.Capture(ctx, err, map[string]any{"http.status": status})
}),
),
)
Sessions & Cookies
github.com/fletchhq/fletch/auth provides server-backed cookie sessions with idle expiration and absolute lifetime caps.
store := auth.DBSessions(db, auth.WithTable("user_sessions"), auth.WithPostgres())
sessions, err := auth.NewSessionCookie(
store,
sessionSecret, // []byte
auth.WithCookieName("app_session"),
auth.WithSecure(cfg.Env == "production"),
auth.WithPath("/"),
auth.WithTTL(24*time.Hour),
auth.WithIdleTimeout(30*time.Minute),
auth.WithAbsoluteTimeout(12*time.Hour),
auth.WithOnSessionRevoked(func(bindingKey string) {
liveHandler.EvictBinding(bindingKey)
}),
)
if err != nil {
return err
}
WithIdleTimeout slides forward on active requests while WithAbsoluteTimeout caps the maximum total lifetime of a session regardless of activity. WithOnSessionRevoked(fn) runs with the session’s binding key when a session is logged out or revoked. Pass it to (*live.Handler).EvictBinding to close the Live pages bound to that session. Inside a Fletch app, app.SessionCookie(secret, opts...) builds the cookie over the app’s session store and already wires revocation to (*fletch.App).EvictLiveBinding, which evicts the binding from every Live handler the app serves.
| Store / Middleware / Method | Role |
|---|---|
auth.MemorySessions() |
In-memory session store for development and tests. |
auth.DBSessions(db, WithTable, WithPostgres) |
SQL-backed session store for SQLite or Postgres. |
Login / LoginSession |
Creates a session and writes the signed session cookie. |
Logout |
Deletes the active session and clears the cookie. |
RevokeUser |
Invalidates all active sessions for a given user ID. |
Authenticate / AuthenticateSession |
Verifies the incoming request cookie and loads the session record. |
Session(r) |
Reads the authenticated session attached to *http.Request. |
BindingKey(r) |
Returns the key Live pages use to bind a page to its session. |
auth.SessionMiddleware |
Loads the session onto the request context on every request. |
auth.RequireUser |
Rejects unauthenticated requests before the handler runs. |
auth.OriginProtection |
Rejects cross-origin state-changing requests based on Origin / Sec-Fetch-Site headers. |
Password Hashing
Hash and verify user passwords with Argon2id via auth.NewPasswordHasher:
hasher := auth.NewPasswordHasher(
auth.WithArgon2(64*1024, 3, 2), // memKiB, passes, threads
)
encoded, err := hasher.Hash(plainPassword)
ok, err := hasher.Verify(plainPassword, encoded)
CSRF Protection
Enable CSRF middleware via auth.CSRF or fletch.CSRF. Both accept the same functional options:
| Option | Behavior |
|---|---|
WithCSRFCookie(name) |
Sets the CSRF cookie name. |
WithCSRFField(name) |
Sets the HTML form field name checked on form posts. |
WithCSRFHeader(name) |
Sets the HTTP request header checked on XHR/fetch requests. |
WithCSRFMaxBodyBytes(n) |
Caps the request body bytes parsed when reading form tokens. |
WithCSRFSecure(bool) |
Marks the CSRF cookie as Secure. |
WithCSRFPath(path) |
Restricts the cookie path attribute. |
Read the token in Go with CSRFToken(ctx) or render a hidden input directly inside a Crest template with <f:csrf />:
<form method="post" action="/account/settings">
<f:csrf />
<input type="text" name="display_name" value={user.DisplayName} />
<button type="submit">Save</button>
</form>
Sealed AEAD Tokens (auth/seal)
github.com/fletchhq/fletch/auth/seal issues short-lived, tamper-proof tokens backed by authenticated encryption. Each token binds a purpose string as associated data, so an email verification token cannot be replayed against a password reset or magic link endpoint.
sealer, err := seal.New(
currentKey,
seal.WithClock(time.Now),
seal.WithPreviousKeys(previousKey),
)
type ResetPayload struct {
UserID string `json:"uid"`
}
token, err := sealer.Seal("password-reset", ResetPayload{UserID: user.ID}, 15*time.Minute)
var payload ResetPayload
err = sealer.Open("password-reset", token, &payload)
Passing seal.WithPreviousKeys(oldKeys...) allows zero-downtime key rotation: Seal always encrypts with the primary key, while Open decrypts tokens minted under the primary key or any listed previous key. Use SealBytes and OpenBytes when encrypting raw byte payloads directly instead of JSON structs.
Signed URLs (auth/signedurl)
github.com/fletchhq/fletch/auth/signedurl generates and verifies HMAC-signed expiring URLs for download routes, invitations, or webhook callbacks.
signer, err := signedurl.New(signingSecret) // []byte, at least 32 bytes
if err != nil {
return err
}
signed, err := signer.Sign("/downloads/report-2026.pdf", 10*time.Minute)
// Verify manually inside a handler:
if err := signer.Verify(r); err != nil {
http.Error(w, "invalid or expired link", http.StatusForbidden)
return
}
// Or protect an entire route or group with middleware:
r.Group("/downloads", signer.RequireSignature())
OIDC, OAuth, JWT, API Keys, and RBAC
Fletch ships focused auth submodules for federated logins, machine credentials, and role-based access control.
OIDC (auth/oidc)
Interactive browser flows use oidc.New(...), which exposes four HTTP handlers: LoginHandler, StepUpHandler(maxAge, acr...) for re-authentication before sensitive operations, CallbackHandler, and LogoutHandler.
For API endpoints accepting OIDC bearer tokens, construct a *oidc.BearerAuthenticator with oidc.NewBearer(issuer, ...). It provides VerifyToken for direct JWT validation against the issuer’s discovery/JWKS endpoints, plus AuthenticateSession and Authenticate for plugging into Fletch’s request authentication pipeline.
OAuth 2.0 (auth/oauth)
auth/oauth handles provider logins with built-in presets and PKCE support:
provider := oauth.New(oauth.Google()) // or oauth.GitHub(), or oauth.OIDC(...)
Use oauth.NewLogin(...) together with the package’s PKCE helpers to start an authorization redirect and exchange the callback code safely.
JWT (auth/jwt)
auth/jwt supports symmetric and asymmetric signing keys (HMACKey, RSAKey, ECDSAKey, Ed25519Key), token creation with Sign, remote/local key sets via NewJWKS, request authentication via Middleware, and stateful refresh token rotation via Issuer. When a previously rotated refresh token is presented again, Issuer returns jwt.ErrRefreshReused so you can revoke the token family.
API Keys (auth/apikey)
auth/apikey manages scoped machine credentials through Manager:
Createmints a new key and stores only its hash.Verifyvalidates a presented key and returns its metadata and scopes.Revokepermanently disables a key.Authorizechecks whether a verified key satisfies a required scope.
Attach Middleware to extract and validate API keys on API route groups, and guard individual routes with RequireScope.
Role-Based Access Control (auth/rbac)
auth/rbac defines static roles and resource policies without an external policy engine:
policy := rbac.NewPolicy(adminRole, memberRole)
policy.RegisterResource("projects", projectRules)
Evaluate permissions programmatically with policy.Authorize, enforce them on route handlers with policy.Require, or attach policy.Middleware to a router group.
Rate Limiting
Protect login routes, APIs, and public forms with the ratelimit package. ratelimit.CacheStore adapts either an in-memory cache or a Redis cache backend, and dedicated Postgres and Redis stores are available when multiple application replicas need shared rate-limit counters.