Guards, user providers, hashing, tokens, the install:auth scaffold, gates and policies. Decisions H4, H5 in brainstorming.md. Phase: ALPHA (password hashing ships in the prototype).
| Concept | Responsibility |
|---|---|
| Guard | How a request is authenticated (session cookie, bearer token) |
| UserProvider | Where users come from (database table via ORM, or custom) |
| Hasher | Password hashing and verification |
| Gate | Named abilities (edit-settings) |
| Policy[T] | Abilities scoped to a model type (update a Post) |
type Authenticatable interface {
AuthID() string // primary key as a string
AuthPassword() string // stored hash
}
type UserProvider[U Authenticatable] interface {
ByID(ctx context.Context, id string) (U, error)
ByCredentials(ctx context.Context, creds map[string]string) (U, error) // never checks the password
}auth.NewORMProvider[models.User](db) is the default provider: ByID by primary key, ByCredentials by every credential except password (columns validated by the ORM), and it stores rehashed passwords (PasswordColumn, default password).
// routes/web.go
users := auth.NewORMProvider[models.User](db)
webGuard := auth.NewSessionGuard("web", users, hash.Default(), auth.NewRememberStore(db))
tokens := auth.NewTokens(db)
tokens.Now = app.Now // the app clock (vukem.WithClock) drives token expiry
apiGuard := auth.NewTokenGuard("api", users, tokens)
r.Post("/login", func(c *web.Ctx) error {
in, err := web.Parse(c, requests.LoginSchema)
if err != nil {
return err
}
if _, err := webGuard.Attempt(c, map[string]string{"email": in.Email, "password": in.Password},
auth.Remember(in.Remember)); err != nil {
return err // 422 on "email": "These credentials do not match our records."
}
return c.Redirect("/dashboard")
})
r.Get("/dashboard", dashboard).Use(auth.Required(webGuard))
r.Group("/api", func(g *router.Group) { g.Use(auth.Required(apiGuard)) /* ... */ })
user, err := auth.User[models.User](c, "web") // in handlers behind RequiredEvery guard that authenticates a request also records auth.Principal(ctx) (guard, id, ok; cleared on logout; combine guard and id length-prefixed or hashed, since either may contain any character), for code that keys data by caller without knowing the guard, such as api.Idempotency.
Attempt(c, creds, auth.Remember(bool)): provider lookup → constant-time hash check →Login. Unknown users still pay for a hash verification against a dummy hash, and both failures return the same 422 error (TestSecurity_A07_LoginErrorsDoNotRevealUsers). Failures emit theauth.login_failedsecurity event.Login(c, u)regenerates the session id (fixation) and stores the user id underauth_<guard>and the owner"<guard>:<id>"(SessionUserID) underweb.SessionUserKey(backfilled on the next request for older sessions), sosession.Manager.RevokeOthers(ctx, owner, keepID)can end the user's other server-side sessions;Logout(c)invalidates the session and deletes the remember-me token.- Logout and the session driver: with
SESSION_DRIVER=cookie(the default) the session lives in the cookie and the server keeps no state, soLogout(c)deletes the cookie in that browser but cannot invalidate a copy of it: a copied cookie stays valid until it expires (SESSION_LIFETIME, 24h by default) or the user's session version changes (seeSessionVersionerbelow). WithSESSION_DRIVER=databasethe session is a server-side row,Logout(c)deletes it, and a copied cookie stops authenticating at once. Pickdatabasewhen logout must end a session that was copied; the framework default stayscookie. - A user type implementing
SessionVersioner(AuthSessionVersion() int64) has its version recorded on login; a session whose version no longer matches the user's is signed out on its next request, whatever the session driver. Bump the version to end every session;RefreshSession(c)re-records it in the current session when that one must stay, and re-issues its remember-me token. Remember-me tokens are bound to the version they were issued under: a bump also ends remember-me logins.SessionValues(guard, user)returns whatLoginstores. A stale session is invalidated whole. DeclareAuthSessionVersionon the value receiver:NewSessionGuardpanics when only*Uimplements it. Existing apps add ausers.session_versioncolumn (BIGINT DEFAULT 0) with a migration before adopting it (see the Sessions page, "Adopting session versions in an existing app"). - A session whose user no longer exists is forgotten: custom
UserProviders must report a missing user fromByIDasauth.ErrUserNotFound(a wrappedorm.ErrNotFoundorsql.ErrNoRowsis accepted too). Any other lookup error (database down) is returned as a 503 andauth.Requiredanswers with it, keeping the session, so an outage neither logs users out nor sends them to the login page (TestSecurity_A04_SessionKeptWhenUserLookupFails). - Remember-me: cookie
remember_<guard>=<id>.<secret>(HttpOnly, SameSite=Lax, Secure unlessInsecureCookies), onlySHA-256(secret)stored inremember_tokens, single use and rotated on every use, 30 days by default (RememberFor). - Impersonation:
Impersonate(c, target, ttl)signs the current user (the actor) in astargetfor at mostttl(regenerated session id, no remember-me token, security eventauth.impersonation_started); the caller authorizes the actor (admins only). Nested impersonation and impersonating oneself are refused withErrImpersonation(409).Impersonator(c)returns the actor id for a banner.StopImpersonating(c)signs the actor back in, unless the actor was deleted or its session version changed meanwhile: then the whole session ends (ErrUnauthenticated). Pastttl(or with an unreadable deadline) the whole session ends on the next request, never falling back to either user (TestSecurity_A01_ImpersonationIsBoundedAndReversible,TestSecurity_A01_ImpersonationExpiresClosed,TestSecurity_A07_StopImpersonatingChecksActorSessionVersion). - Rehash on login when
hasher.NeedsRehash(e.g. bcrypt → argon2id) and the provider implementsPasswordUpdater.
- Opaque tokens
<prefix><id>.<secret>(crypto/rand.Text()).tokens.Prefix = "vk_"(set by theinstall:authscaffold; pick one specific to your app) starts every new token so secret scanners can match leaks: register a custom pattern such asvk_[A-Z2-7]{26}\.[A-Z2-7]{26}in GitHub secret scanning or gitleaks. The prefix is up to 32 letters, digits or underscores ending in_(Createfails otherwise); tokens issued without it or under an earlier prefix stay valid (TestSecurity_A04_TokenPrefixForSecretScanning).tokens.CreateWithID(ctx, id, userID, name, abilities, ttl)issues a token under an id you choose (1 to 64 ASCII letters, digits or hyphens; no_or., whichFindreads as the prefix and the separator); a stored id fails on the primary key (TestTokensCreateWithIDRoundTrips,TestTokensCreateWithIDRefusesIDsFindCannotSplit).tokens.CreateWith(ctx, userID, name, abilities, ttl, auth.CreateOptions{ID, Resource})also stores a free-formResource(up to 255 bytes: a project or tenant id) thatFindandListreturn inToken.Resource; the token does not enforce it, the app compares it with the resource the request names. It needs the nullableresourcecolumn: addauth.TokensResourceMigration(id)to the migrations (a table without it keeps working for everything else, andCreateWithwith aResourcefails with an error naming the migration; the column is probed on every read until it is found, so a migration takes effect without a restart). An emptyResourcemeans the token carries none; it must not be read as "any resource" when the app relies on resource scoping: refuse a request for a resource unless the token'sResourceequals it, or the app deliberately allows unscoped tokens (TestTokensCreateWithResourceRoundTrips,TestTokensResourceNeedsMigration,TestTokensResourceAppearsAfterMigrationWithoutRestart). access_tokensstoresSHA-256(secret), name, abilities (JSON),last_used_at(updated at most once a minute), optional expiry andrevoked_at(TestSecurity_A04_TokensStoredHashed).- Revocation is soft:
Revoke,RevokeForandRevokeAllsetrevoked_at(a second revoke keeps the first time) and keep the row, soListshows revoked tokens withRevokedAt;Findrefuses a revoked or expired token only after the same digest comparison a valid one pays, and an unknown id compares against a placeholder digest (TestSecurity_A07_RevokedTokenRejected).Prune(ctx, cutoff)hard-deletes tokens revoked beforecutoffor expired before the earlier ofcutoffand now, so a future cutoff never deletes a live token. - Upgrading: tables created before v0.26.0 lack
revoked_at. Until it exists every token is refused with 503 (fail closed), andRevoke,RevokeForandRevokeAlldelete the rows instead (revoking stays possible, also inside a transaction: the column is probed first, since a failedUPDATEwould abort a PostgreSQL transaction); one error namingauth.TokensRevokedAtMigrationis logged perTokens(the guard uses the request logger, revokesTokens.Log, defaultslog.Default()). The missing column is recognised by SQLSTATE42703(PostgreSQL),no such column(SQLite) or error1054(MySQL/MariaDB). Addauth.TokensRevokedAtMigration(id)to the app's migrations; it adds the column only when missing (schema.Schema.HasColumn) and itsDownis a no-op (TestTokensRevokedAtMigration,TestTokensRevokeOnLegacyTable;drivers/postgresTestTokensSoftRevoke,drivers/mysqlTestTokensLegacyTable). - Token and JWT guards read the credential with
auth.BearerToken(r): theBearerscheme is case-insensitive (RFC 7235), sobearer <token>works, and surrounding spaces are trimmed (TestTokenGuardBearerSchemeCaseInsensitive). - The token guard answers a missing, unknown, wrong, expired or revoked token with 401, and a failing store (database down, missing column, a user lookup error other than not found) with 503, like the session guard: an outage is never reported as bad credentials (
TestSecurity_A04_TokenGuardStoreFailureIs503,TestTokenGuardUserLookupErrors).auth.Requiredstops at the first guard that fails with something other than 401, so on routes that accept both a session and a token list the session guard first:auth.Required(webGuard, apiGuard). With the token guard first, a request carrying a valid session and anyBearerheader is answered 503 while the token store fails. Code that callstokens.Finditself makes the same split witherrors.Is(err, auth.ErrInvalidToken)(401); any other error is the store (503) (TestTokensFindSeparatesInvalidTokensFromStoreFailures). tokens.Create(ctx, user.AuthID(), "cli", []string{"posts:read"}, 30*24*time.Hour)returns the plain token once. Attlof0means no expiry: the token stays valid until revoked, so pass a ttl unless that is intended (theinstall:apiscaffold issues 30-day tokens);List(ctx, userID)(no secrets, revoked tokens included),RevokeFor(ctx, userID, id)(owner-checked: use it when the id comes from user input;falsefor another user's, unknown or already revoked token),Revoke(ctx, id)(unchecked, for the current token),RevokeAll(ctx, userID);auth.CurrentToken(c, "api"),auth.TokenCan(c, "api", "posts:read");"*"grants every ability.- Hashes are compared with
subtle.ConstantTimeCompare; rejected tokens emittoken.rejected.
Standard library only. jwt.Sign(key, jwt.Claims{Subject, Issuer, Audience, ExpiresAt, NotBefore, IssuedAt, ID, Extra}) (jwt.SignTyped(key, "at+jwt", claims) sets another typ header, which VerifyOptions.Types then requires) with jwt.HS256(kid, secret) (≥ 32 bytes), jwt.RS256(kid, rsaKey) (≥ 2048 bits), jwt.ES256(kid, p256Key) or jwt.EdDSA(kid, ed25519Key).
jwt.NewVerifier(keys, jwt.VerifyOptions{Issuer, Audience, Algorithms, Leeway, AllowMissingExpiry, Nonce}): the headeralgmust be allowed and equal the algorithm of the key picked bykid, so HMAC-with-a-public-key confusion andnoneare impossible (TestSecurity_A04_JWTAlgorithmConfusion);expis required by default,nbf/iatchecked with 30s leeway,iss/audexact;Nonce, when set, must equal thenonceclaim (constant-time; a missing or non-string claim is refused), which binds an ID token to the sign-in that started it: build the verifier per request with the client's nonce, and prefer the authorization-code + PKCE flow (social) over ID tokens passed by a native app through a custom URI scheme, which another app can intercept (TestSecurity_A07_JWTNonceBinding); duplicate JSON members and tokens over 8 KiB are rejected. Every failure wrapsjwt.ErrInvalid, except a key set that could not be consulted (aRemoteJWKSfetch failing with no cached key), which wrapsjwt.ErrKeysUnavailable; custom key sets wrap it for their own outages.- Key sets:
jwt.StaticKeys(current, previous...)for rotation;&jwt.RemoteJWKS{URL: issuer + "/.well-known/jwks.json"}caches an identity provider's keys, refetches on an unknownkidat most once a minute (MinRefresh, which also holds the retry after a failed fetch, so a failing provider is not hit on every token;jwt.ErrKeysUnavailableis the answer meanwhile) and refreshes hourly.RemoteJWKS.Clientis ajwt.Doer(Do(*http.Request), which*http.Clientsatisfies), so an outbound gate can fetch the keys; aDoerthat is not a*http.Clientmust apply its own redirect policy. A verifier over aRemoteJWKSneedsAudienceandIssuer: the provider signs tokens for all of its clients with the same keys, so without them a token issued to another app would pass. Missing either,verifier.Err()says which,jwt.NewGuardpanics at boot, and everyVerifyfails with a barejwt.ErrInvalid(the detail never reaches clients). Custom key sets that wrap aRemoteJWKSimplementjwt.SharedKeySet(SharedKeys() bool; embedding*jwt.RemoteJWKSforwards it) to get the same check.InsecureSkipAudience/InsecureSkipIssueropt out (dangerous) (TestSecurity_A07_RemoteJWKSRequiresAudienceAndIssuer);jwt.PublicJWKS(keys...)builds your own JWKS document (HMAC keys are never published). jwt.NewGuard[User]("api", verifier, provider)implementsauth.Checker(auth.Required(guard));jwt.ClaimsFrom(c, "api")exposes the claims; rejected tokens emitjwt.rejected. Like the token guard it fails closed: an invalid token or asubwith no user (auth.ErrUnauthenticated,auth.ErrUserNotFound,orm.ErrNotFound,sql.ErrNoRows) is 401, a key set outage or any other user lookup error is 503, andauth.Requiredstops there (TestSecurity_A04_JWTGuardOutageIs503). It implementsauth.FailClosedChecker(Authenticate(c) error), which custom guards implement to get the same behaviour.- Refresh tokens:
jwt.NewRefreshTokens(db)withjwt.RefreshTokensMigration(id)stores onlySHA-256of opaque tokens;Issue(ctx, userID)starts a family,Rotate(ctx, token)consumes it and returns the user and a new token, atomically (one winner among concurrent rotations,TestSecurity_A07_RefreshConcurrentRotationSingleWinner); presenting a consumed token returnsjwt.ErrRefreshReusedand revokes the whole family.Revoke(ctx, token)(logout) andRevokeUser(ctx, id)(password change).
| Middleware | Effect |
|---|---|
auth.Required(guards...) |
first guard that authenticates wins; JSON clients get 401 with WWW-Authenticate: Bearer, browsers a redirect to the route named login (intended GET URL kept in the session under auth.IntendedKey). When every guard is an auth.APIGuard (token and JWT guards), nobody is redirected: the 401 is always problem+json, whatever Accept or the session cookie says; the same under auth.ProblemJSON, which must be mounted before Required. A guard failing with 503 (store down) stops the list: put the session guard before the token guard |
auth.Guest(guards...) |
sends logged-in users to the route named home |
auth.Verified(guard) |
403 unless the user implements EmailVerified() bool and returns true |
auth.Ability(guard, abilities...) |
403 unless the token grants every ability (authz.denied event); problem+json for an auth.APIGuard |
auth.ProblemJSON |
route-group setting for APIs that are not only auth.APIGuards (a session fallback, a custom authenticator or scope check): mount it first (g.Use(auth.ProblemJSON, auth.Required(apiGuard, webGuard))). Below it Required, Ability and Verified never redirect, and every 401 and 403 rendered by middleware (theirs, or yours through web.Fail) is RFC 9457 problem+json whatever Accept says, like the built-in API guards. Middleware mounted before it is not affected, so Required ahead of it still redirects. The forcing covers any 401/403 from middleware below it, not only authentication (a CSRF or rate-limit 403 too). Other statuses and handlers keep negotiating; a custom guard can instead implement auth.APIGuard (APIOnly()) |
app.Client(t).ActingAs("web", user) starts a logged-in session (with the user's session version), .WithSession(values) adds values such as an app's own login stamp; .WithToken(plain) sends a bearer token.
| Driver | Default params | Notes |
|---|---|---|
| argon2id (default) | m=64 MiB, t=1, p=4, 16-byte salt, 32-byte key | PHC string $argon2id$v=19$m=…,t=…,p=…$salt$hash |
| bcrypt | cost you choose (12 recommended) | inputs over 72 bytes are rejected (ErrPasswordTooLong), never truncated |
hash.Default(), hash.Argon2id(params) (start from hash.DefaultArgon2Params()), hash.Bcrypt(cost), hash.Fake() (tests). Verify reads both formats; NeedsRehash is true for other parameters or algorithms. Both come from golang.org/x/crypto.
vukem install:auth copies user-owned code into the project (Fortify-style), registers its migrations and routes, and runs go mod tidy:
app/models/user.go User (AuthID, AuthPassword, EmailVerified)
app/accounts/{accounts,users,passwords}.go guards, registration, verification, password resets
app/accounts/{messages.go,lang/} auth messages in en, es, pt-BR (accounts.T)
app/controllers/account/*.go login, register, logout, forgot/reset password, verification, dashboard
app/requests/auth.go z schemas (password ≥ 12 characters, confirmation)
app/mail/auth.go VerifyEmail, ResetPassword and AccountExists mailables
database/migrations/*_create_users_table.go, *_create_auth_tables.go (remember, access and reset tokens)
resources/views/auth/*.html, resources/views/mail/{verify_email,reset_password,account_exists}.html
routes/auth.go appended to routes.All()
tests/auth_test.go the whole flow, run by go test
tests/auth_messages_test.go every message translated
| Flow | Behaviour |
|---|---|
| Register | the same answer for new and existing emails (redirect to /register/check-email, no validation error, no login): a new email gets the account and a verification mail; an existing one gets a "someone tried to sign up" notice (AccountExists, at most one per hour per address through the cache, keyed by a hash of the address) and nothing is created or changed. Both paths hash the password with argon2id and queue one mail (SendLater), so the timing does not reveal accounts either. A cache error on that path skips the notice and is logged, never returned, so an outage does not reveal accounts either. Sign-up is limited to 10 per 10 minutes per IP and 5 per hour per address (keyed by a SHA-256 of the address, through app.RateLimiters, so RATE_LIMIT_STORE=cache shares it); the limit counts requests, not accounts, so it answers 429 alike for new and existing addresses. The per-address limit can keep a specific address from signing up for an hour (anyone can spend its budget), without revealing whether it has an account (TestSecurity_A07_SignupIsEnumerationSafe, TestSecurity_A07_SignupRateLimited, TestSecurity_A07_SignupCacheOutageIsNoOracle, generated TestRegisterDoesNotRevealAccounts, TestRegisterThrottle, TestRegisterSurvivesCacheOutage) |
| Login | Attempt with remember-me, intended URL, 5 attempts per minute per email + IP (ratelimit) (and 30 per minute per IP, plus 20 per 10 minutes per account), same error for unknown users. Signed-in pages (dashboard, 2FA settings, billing, admin panel) also need a verified email (auth.Verified): an unverified login lands on the verification notice, so an account someone pre-registered with another person's address is useless until that person verifies it (and a password reset then ends the squatter's sessions). POST /api/v1/tokens answers 403 to unverified users, and install:admin admins need a verified ADMIN_EMAILS address |
| Email verification | signed link (signed package, HMAC + 1 hour expiry) that needs the login of its account: signed out, it leads to /login, which comes back to the link (kept as the intended URL, also after a 2FA challenge or a social sign-in) and verifies it; signed in as another account it answers 403. The signature is checked after the login, so a link that expired meanwhile leads to the verification notice with an "expired, send a new one" message (auth.verification_expired), and a tampered one is a 403 with the url.signature_invalid event; opening the link of an already verified account goes to the dashboard without ending any session. Resend (signed in) limited to 3 per minute. Whoever merely owns the mailbox cannot verify an account someone else created with the address: the link verifies nothing without that account's password, the squatter's account stays unverified (and useless, see Login), and the owner's own sign-up attempt gets the "sign in or reset your password" notice, whose reset ends the squatter's access. The link carries a SHA-256 of the address (email_hash) and is void once the email changes. Verifying ends every other session (session version bump), remember-me token and API token of the account, and the verifier keeps their session (RefreshSession) (TestSecurity_A07_VerificationLinkRequiresLogin, generated TestRegisterAndVerifyEmail, TestVerificationEndsOtherSessions, TestVerificationLinkBoundToEmail, TestExpiredVerificationLinkOffersANewOne, TestVerifiedLinkKeepsOtherSessions) |
| Forgot / reset password | same answer for unknown emails; random token stored as SHA-256, 1 hour, single use, and a SecretParams("token") route parameter so logs show {token}; reset ends every session on every session driver (users.session_version bumped with the password; server-side records deleted), remembered session and API token (Accounts.RevokeOtherSessions; call it too if you add a password change form) |
| Logout | session invalidated, remember-me token deleted |
Since sign-up never says "this email is taken", a user who forgot they have an account learns it from the notice mail, which links to the login and password reset pages. The trade-off: a sign-up form that cannot tell users their email is taken, and a mail queue that must work (QUEUE_CONNECTION=database in production). Apps that ran install:auth before v0.26.0 keep the old flow (409 for a taken email, login before verification) until they port Register, Verify, routes/auth.go and the new AccountExists mail, or re-run install:auth --force (and install:admin / install:billing / install:api for their verified-email checks). The examples/ apps pin an older vukem and keep the old flow. Apps that ran install:auth before v0.27.0 verify the link signed out; to require the login, re-run install:auth --force (or port Verify in app/controllers/account/verification.go, the verification.verify route in routes/auth.go, which now uses required instead of the signature middleware, the new auth.verification_expired message, the social callback's intended-URL redirect in routes/social.go, and the generated tests), as described in the upgrade guide.
Flash messages, controller errors and mail subjects go through accounts.T(ctx, key), with English, Spanish and Brazilian Portuguese catalogs in app/accounts/lang/<locale>/*.json (keys auth.*; --2fa and --social add two_factor.json and social.json). T uses the request locale that i18n.Middleware resolves when the app uses vukem.WithTranslations, and English otherwise. A key in the app's own catalog for that locale or its language (resources/lang/pt-BR.json, then pt.json) wins, so the app can reword a message or add a locale without editing the scaffold. Field messages of the z schemas in app/requests and the views stay in English. Errors from the framework itself (failed login, unverified email, missing token ability, social sign-in, orm.Unique) carry their own keys and are translated by the built-in catalogs (i18n); the login error stays the same for unknown users and wrong passwords in every locale. tests/auth_messages_test.go checks that every key exists in every locale. Mailables built without a Subject keep the English one.
The reset link mail is queued (mailer.SendLater), so the forgot-password answer does not wait for the mail server and its timing does not tell known emails from unknown ones. That needs a real queue: set QUEUE_CONNECTION=database in production (memory also answers fast, but a restart loses queued reset mails, so users may need to ask again); with the default sync the mail is still sent during the request.
Existing projects created before routes.All() get the exact lines to add printed instead. --force overwrites existing files.
vukem install:auth --social github,google (also on a project that already ran install:auth) adds routes/social.go (/auth/{provider}/redirect and /callback), the social_accounts model and migration (unique provider + provider id), accounts.NewSocial (credentials from SOCIAL_<NAME>_CLIENT_ID/_SECRET, also appended to .env.example) and FindOrCreateFromSocial: an existing link signs in; a provider-verified email links to the existing account; an unverified email that matches an account is refused (409) so a provider account cannot take over a password account; when a provider-verified email links to a local account that was never verified, the local password is replaced with a random one and its sessions, remember-me and API tokens end (like a password reset), since they may belong to whoever signed up first with the address; otherwise a new user is created. After the sign-in the callback goes back to the intended URL (such as a verification link), or to /dashboard. Generated tests use vukemtest.FakeSocial(social.User{...}), which only works in test apps.
vukem install:auth --2fa (also on a project that already ran install:auth, like --social) adds Fortify-style TOTP two-factor authentication built on auth/totp (RFC 6238: SHA-1, 6 digits, 30 s, the authenticator-app defaults), for the HTMX starter and for the Inertia React, Vue and Svelte starters:
Recovery codes are stored as hex SHA-256 of totp-recovery: plus the code trimmed and upper-cased; totp.HashRecoveryCode(code) returns that form, so codes imported from another auth system work with totp.UseRecoveryCode.
app/models/two_factor.go TwoFactor: the 2FA columns of users (Table() = "users")
app/accounts/two_factor.go enable, confirm, verify, recovery codes, disable, pending login
app/controllers/account/two_factor*.go settings page and login challenge handlers
app/requests/two_factor.go code, challenge and password confirmation schemas
database/migrations/*_add_two_factor_columns.go
resources/views/auth/two-factor*.html or resources/js/pages/Auth/TwoFactor*.{tsx,vue,svelte}
routes/two_factor.go appended to routes.All()
tests/two_factor_test.go the whole flow, run by go test
It also patches the user-owned Login handler (Validate, then the challenge, then Login), links the settings page from the dashboard and, when routes/social.go exists (before or after --2fa), makes social sign-in stop at the challenge too. If Login was rewritten by hand the command fails before writing anything and prints the change to make, so 2FA is never installed without being enforced.
| Flow | Behaviour |
|---|---|
| Storage | two_factor_secret (orm.Encrypted[string]) and two_factor_recovery_codes (orm.Encrypted[[]string] of SHA-256 hashes) are encrypted with APP_KEY, never plaintext; two_factor_confirmed_at; two_factor_last_step. TwoFactor is its own model, so the secret never reaches User or the shared auth.user prop |
Enable (GET/POST /user/two-factor) |
logged-in users get a new secret: QR code (inline SVG from totp.QR of the otpauth:// URI, issuer APP_NAME) and the setup key for manual entry. A confirmed setup is never replaced (409), so enabling again cannot switch 2FA off without the password |
Confirm (POST /user/two-factor/confirm) |
2FA is on only after a valid code; then 8 recovery codes are shown once (flashed in the encrypted session, only hashes are stored); every other session of the user ends (Accounts.RevokeOtherSessions, then Web.RefreshSession keeps the current one) |
Recovery codes (POST /user/two-factor/recovery-codes) |
regenerate after checking the current password (ConfirmPasswordSchema; wrong one: 422 on password, auth.2fa_failed with stage=recovery_codes): the old ones stop working, the new ones are shown once; the page shows how many are left |
Disable (POST /user/two-factor/disable) |
needs the current password |
| Login | a correct password for a user with confirmed 2FA does not log in: the session id is regenerated, the pending user id and the remember-me choice are stored, and the browser goes to /two-factor-challenge. The pending login expires after 5 minutes (accounts.TwoFactorChallengeTTL) |
Challenge (GET/POST /two-factor-challenge) |
an app code (totp.Validate against two_factor_last_step, then the matched step is stored) or a recovery code (consumed, the remaining hashes stored) logs in with the remember-me choice and goes to the intended URL |
| Replay | a code whose step is at or before the last accepted one is refused, including the code used to confirm; codes are checked inside a transaction that first writes the row, so concurrent requests with the same code run one after the other and one wins |
| Throttling | challenge, confirm, recovery codes and disable: 5 per minute per user + IP (ratelimit, 429 with Retry-After) |
| Events | failed codes and passwords log the auth.2fa_failed security event (user_id, stage: confirm, challenge, disable) |
totp.QR (SVG) and totp.QRMatrix (modules) encode any text in byte mode at error correction level M, versions 1 to 40: up to 2331 bytes (long otpauth:// URIs, PIX BR Codes); longer text returns totp.ErrTooLong.
The raw SVG is inserted with template.HTML (HTMX) or the framework's raw-HTML binding (dangerouslySetInnerHTML, v-html, {@html}): safe only because totp.QR writes it itself from server data; never do that with user input. Generated tests compute codes with totp.Code(secret, time.Now(), totp.Options{}).
auth/webauthn verifies WebAuthn Level 3 registration and authentication ceremonies, standard library only: a minimal CBOR decoder (definite lengths, depth and length bounds), COSE keys for ES256 (P-256), EdDSA (Ed25519) and RS256 (at least 2048 bits), and attestation none (provenance is not verified; RegistrationOptions asks for none). The package is stateless; the app stores challenges and credentials.
RelyingParty{ID, Name, Origins, InsecureSkipUserVerification};Validaterefuses origins outside the RP ID andhttpexcept onlocalhost. User verification is required unlessInsecureSkipUserVerificationis set.NewChallenge() string(32 random bytes, base64url, so any session store keeps it as is) andNewUserHandle() []byte(random; never a database id or an email).rp.RegistrationOptions(user, challenge, exclude)andrp.AssertionOptions(challenge, allow)return the JSON forPublicKeyCredential.parseCreationOptionsFromJSON/parseRequestOptionsFromJSON(discoverable credentials,residentKey: "required").rp.VerifyRegistration(challenge, user, body)checks the browser'scredential.toJSON()and returns theCredentialto store (id, COSE public key, algorithm, sign count, user handle, backup flags, transports).ParseAssertion(body)exposes the credential id and user handle for the lookup;rp.VerifyAssertion(challenge, cred, a)returns the credential with the new sign count to save.
Checks and errors: challenge (ErrChallenge, an empty stored challenge never matches), origin and cross-origin iframes (ErrOrigin), RP ID hash (ErrRPID), user presence and verification (ErrUserPresence, ErrUserVerification), attestation format (ErrUnsupportedAttestation), key type and algorithm agreement (ErrUnsupportedKey), credential id and user handle (ErrCredential), signature (ErrSignature), sign count regression (ErrSignCount, both counters at 0 is a synced passkey). The app pulls the challenge out of the session before verifying (single use), throttles the endpoints and keeps a recovery path. Site page: site/content/docs/security/passkeys.mdx.
auth/webauthn/webauthntest is a software passkey for tests: webauthntest.New(origin), then Create(optionsJSON) and Get(optionsJSON) return the JSON the browser would post (ES256, attestation none, user verified, sign count +1 per Get).
vukem install:auth --passkeys (also on a project that already ran install:auth) adds passkey sign-in next to the password, for every starter (the endpoints answer JSON, so the page that calls them is yours):
- Migration:
users.passkey_handle(random user handle, set on first use) andpasskey_credentials(user_id, unique base64urlcredential_id, COSEpublic_key,algorithm,sign_count,user_handle, backup flags,transports,name,last_used_at). accounts.NewPasskeys(acc, app): the relying party comes fromAPP_URL(host = RP ID, origin = the only allowed origin) andValidateruns at boot, so plainhttpon a public host is a boot error.- Routes (
routes/passkeys.go):GET /user/passkeys(list),POST /user/passkeys/options(needspassword),POST /user/passkeys(name+credential),POST /user/passkeys/{id}/delete(needspassword),POST /passkeys/login/optionsandPOST /passkeys/login(answers{"redirect": ...}). Settings routes need a verified user; password checks are limited to 5 per minute per user + IP, sign-in to 10 per minute per IP. - Each challenge is pulled out of the session before verifying (single use), and that single-use challenge is what stops a replayed assertion; the sign count is also saved with a compare-and-set, which detects a cloned authenticator only when the authenticator counts (synced passkeys always send 0); every refused ceremony answers the same 422 on
credentialand logsauth.passkey_failedwith the reason. - Recovery path: a passkey is added and removed only after the current password is confirmed, and password sign-in and reset stay on, so losing a device never locks the account. Social-only users set a password (forgot password) first. A passkey sign-in with user verification counts as two factors: users with
--2faskip the code step. This holds only whileInsecureSkipUserVerificationis off (the default). - Generated tests (
tests/passkeys_test.go) drive real ceremonies withauth/webauthn/webauthntest, a software ES256 passkey:TestPasskeySignIn,TestSecurity_A07_PasskeyChallengeIsSingleUse(replayed registration and sign-in, older challenge),TestSecurity_A07_PasskeyIsScopedToItsUser(another user's passkey is not listed nor deletable, an unregistered credential does not sign in) andTestSecurity_A07_PasskeyChangesNeedThePassword.
Browser side:
// Add a passkey (signed in; the password is confirmed first).
const opts = await post("/user/passkeys/options", { password });
const created = await navigator.credentials.create({
publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(opts),
});
await post("/user/passkeys", { name: "Laptop", credential: created.toJSON() });
// Sign in (usernameless).
const req = await post("/passkeys/login/options", {});
const got = await navigator.credentials.get({
publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(req),
});
const { redirect } = await post("/passkeys/login", got.toJSON());
location.assign(redirect);post is your fetch wrapper that sends JSON with the CSRF token header and returns the parsed body.
Ally-style OAuth2/OIDC sign-in, standard library only (no x/oauth2).
key, err := app.DeriveKey("social.state", 32) // config.ErrKeyMissing without APP_KEY
if err != nil {
return err
}
s := social.New(key, // panics on a key shorter than 32 bytes
social.GitHub(social.Config{ClientID: id, ClientSecret: secret, RedirectURL: "https://app.test/auth/github/callback"}),
social.Google(googleCfg), // OIDC
social.Microsoft("common", microsoftCfg), // OIDC (Entra ID)
social.GitLab(gitlabCfg), social.Discord(discordCfg),
social.OIDC("okta", "https://example.okta.com", oktaCfg), // any OIDC issuer
social.LinkedIn(linkedinCfg), // OIDC
social.X(xCfg), // OAuth 2.0 + PKCE, Basic auth at the token endpoint; no email
apple, // social.Apple(social.AppleConfig{Config, TeamID, KeyID, PrivateKey: p8})
).WithPreviousKeys(app.DerivePreviousKeys("social.state", 32)...) // APP_KEY rotationSign in with Apple signs its client secret (an ES256 JWT, cached for an hour) with the .p8 key, and answers with response_mode=form_post: the callback is a cross-site POST from appleid.apple.com. Register POST on the callback route, serve the app over HTTPS (the state cookie becomes SameSite=None; Secure, and Redirect refuses to run with InsecureCookies), and add https://appleid.apple.com to CSRF_TRUSTED_ORIGINS. Apple sends the user's name only on the first sign-in (read from the posted user field). install:auth --social apple,linkedin wires both; Apple reads SOCIAL_APPLE_CLIENT_ID, SOCIAL_APPLE_TEAM_ID, SOCIAL_APPLE_KEY_ID and SOCIAL_APPLE_PRIVATE_KEY_PATH.
r.Get("/auth/{provider}/redirect", func(c *web.Ctx) error {
return s.Redirect(c, c.Param("provider")) // 404 for unknown providers
})
r.Get("/auth/{provider}/callback", func(c *web.Ctx) error {
u, err := s.User(c, c.Param("provider"))
if err != nil {
return err // 400 bad/expired state, 403 access denied, 502 provider failure
}
user, err := actions.FindOrCreateFromSocial(c.Context(), db, u) // user-owned code from install:auth --social
if err != nil {
return err
}
return webGuard.Login(c, user)
})| Feature | Detail |
|---|---|
| Flow | Authorization Code + PKCE (S256) for every provider; htmx requests get HX-Redirect so the browser navigates |
| CSRF / replay | random state, PKCE verifier and OIDC nonce in a 10-minute, HMAC-signed, HttpOnly, SameSite=Lax cookie bound to the provider; state compared in constant time; the cookie is cleared and the state recorded as used, so a replayed callback fails (TestSecurity_A07_SocialStateMismatch, TestSecurity_A07_SocialReplayAndPKCE). Used states live in process memory unless s.States is set to a cache store (c, _ := app.Cache(); s.States = c.Store(), keys social:state:<state>); set it when the app runs more than one replica, with CACHE_STORE=database or Redis. In production the store must be persistent and shared: the memory cache store is bounded (CACHE_MAX_ENTRIES) and evicts entries, and an evicted state could be replayed until its cookie expires. A store error refuses the callback (503) |
| OIDC | discovery document, JWKS cache refreshed once for unknown kid, only RS256/ES256 (never none/HS*), RSA keys ≥ 2048 bits, checks iss (Microsoft {tenantid} templates), aud/azp, exp/iat with 1 minute leeway, nonce (TestSecurity_A07_IDTokenChecks) |
| User | social.User{Provider, ID, Email, EmailVerified, Name, Nickname, AvatarURL, Token{Access, Refresh, Expiry, Scopes}, Raw} |
| Email trust | EmailVerified only when the provider vouches: GitHub primary verified address, GitLab confirmed_at, Discord verified, OIDC email_verified (Microsoft: xms_edov). Link accounts by (Provider, ID), by email only when verified |
| Allowlist | s.Allow func(ctx, social.User) error refuses a provider user before any account lookup (social.ErrNotAllowed, 403); nil admits everyone (TestAllowHook) |
| Stateless | s.UserFromToken(ctx, "google", accessToken) for API/SPA flows (profile/userinfo endpoint) |
| Options | social.WithEndpoints(...) (GitHub Enterprise, self-hosted GitLab, tests), social.WithAuthParams(...), Config.Scopes, OIDC(...).AuthParams(...), social.OAuth2(name, cfg, endpoints, scopes, mapUser) |
| Security | a provider error other than access_denied answers social.ErrProvider (400, fixed message) and logs the sanitized code, so a crafted callback link cannot put text on the page (TestSecurity_A03_SocialProviderErrorNotReflected); redirect URL fixed in config, provider calls through a client with a 10 s timeout and 1 MiB response limit, tokens never logged |
A private, single-owner app admits only some provider users. Set s.Allow before the first sign-in: it runs after the provider returns the user and before User or UserFromToken hands it back, so FindOrCreateFromSocial never sees a refused user and no account row or session is created. Return social.ErrNotAllowed (or an error wrapping it) to refuse the user: 403, key social.not_allowed, reason never shown. Any other error means the check itself failed (a database outage, say) and answers 503 without refusing, logged as a warning; redirect to the login page with a flash message in the callback instead of rendering the error. Nil admits everyone.
s.Allow = func(ctx context.Context, u social.User) error {
if u.EmailVerified && u.Email == ownerEmail {
return nil
}
return errors.New("not the owner")
}
r.Get("/auth/{provider}/callback", func(c *web.Ctx) error {
u, err := s.User(c, c.Param("provider"))
if errors.Is(err, social.ErrNotAllowed) {
_ = c.Flash("error", social.ErrNotAllowed.LocalizedText(c.Context()))
return c.Redirect("/login")
}
...
})Accounts created before the rule keep their sessions. Add auth.Allow(webGuard, func(u User) bool { return u.Email == ownerEmail }) after auth.Required(webGuard) on the protected routes: it logs out a refused user and answers 403 (auth.not_allowed).
Apple (social.Apple, form-post callback), LinkedIn (social.LinkedIn) and X (social.X) are built in. X sends no email address, so install:auth --social x is refused (exit 2): the scaffold creates and links accounts by a provider-verified email, and an X sign-in could never create one (TestSecurity_A07_SocialRefusesProvidersWithoutEmail). Wire social.X yourself, for example to link X to an account that is already signed in, keyed by (Provider, ID). social.Fake(name, callbackURL, user) is a provider for tests.
Package authz, generic over your user type. Decisions fail closed: an ability or policy that was never registered denies (403) and the cause is logged (TestSecurity_A01_UnregisteredPolicyDenies).
gate := authz.New(func(ctx context.Context) (*models.User, error) {
u, err := auth.UserFrom[models.User](ctx, "web") // who is asking; the session guard stores a value
return &u, err
})
gate.Define("edit-settings", func(ctx context.Context, u *models.User) bool { return u.Role == "admin" })
gate.DefineResult("see-billing", func(ctx context.Context, u *models.User) authz.Result { return authz.DenyAsNotFound() })
r.Services().Authorizer = gate // enables c.Authorize and {{can}}
if err := c.Authorize("edit-settings", nil); err != nil {
return err // 401 without a user, 403 denied, 404 for DenyAsNotFound
}// app/policies/post_policy.go — vukem make:policy Post
type PostPolicy struct{}
func (PostPolicy) Update(ctx context.Context, u *models.User, p *models.Post) authz.Result {
if u.ID == p.UserID {
return authz.Allow()
}
return authz.DenyAsNotFound() // 404 instead of 403
}
func (PostPolicy) Create(ctx context.Context, u *models.User) bool { return u.Verified() } // type-level ability
// app/policies/registry.go (make:policy appends here)
func All() []authz.Policy { return []authz.Policy{authz.For[*models.Post](PostPolicy{})} }
if err := gate.Register(policies.All()...); err != nil { // at boot: signatures are checked here
return err
}
if err := c.Authorize("update", post); err != nil { return err }
if err := c.Authorize("create", (*models.Post)(nil)); err != nil { return err }- Policies are found by the subject's Go type; a
models.Postvalue (a template ranging over[]models.Post) uses the*models.Postpolicy on a shallow copy (slices, maps and pointers inside it stay shared); a type with its own value policy keeps it. Ability names map to methods ("update"→Update). Methods returnauthz.Result(Allow,Deny(msg),DenyAsNotFound) orbool; other methods on the policy are ignored. gate.Before(func(ctx, u, ability) *authz.Result)decides first (super-admins).gate.Allows(ctx, u, ability, subject)for code outside requests.- Denials through
c.Authorizeemit theauthz.deniedsecurity event. Without anAuthorizerevery check denies. - Templates:
{{if can "update" .Post}}…{{end}},{{if can "edit-settings"}}…{{end}}.
Login and password reset are throttled by default via ratelimit (GCRA in memory; drivers/redis provides a limiter shared by every server).