Skip to content
Authentication reference

Authentication reference

Packages auth, auth/password, auth/social and auth/rbac. How-to: Authentication, Authorization, Roles and permissions. Settings: configuration reference.

Setup

APIDoes
auth.AuthenticatableAuthID() string and AuthPassword() string, implemented by the app’s user type
auth.Users[U]{ByID, ByLogin, RememberToken, SetRememberToken, SetPassword, Disabled, SessionKey, SetSessionKey, TwoFactor, SetTwoFactor}How to find users (required: ByID, ByLogin; they return db.ErrNotFound or auth.ErrUserNotFound), store remember-me tokens and upgraded hashes; which accounts are disabled (Disabled); the session key sessions are bound to (SessionKey and SetSessionKey, both or neither); the two-factor state, stored encrypted (TwoFactor and SetTwoFactor, both or neither)
auth.New(app, users, opts...)*auth.Auth[U] from AUTH_* and APP_KEY; needs cache.New first; provided to the app; once per app. Options as NewWithConfig’s, after its own, and auth.WithDefaultHomeURL(path): AUTH_HOME_URL’s default
auth.NewWithConfig(cfg, users, enc, opts...)Without an app; auth.WithLogger, auth.WithInsecureCookies, auth.WithIssuer(name) (two-factor setups’ issuer; auth.New uses APP_NAME)
auth.Migrations()The api_tokens table, for migrate.New

Middleware

APIDoes
a.MiddlewareMakes the request’s user available (from the session or a remember-me cookie); after the session middleware
a.RequireLogged-in users only: guests asking for a page are redirected to AUTH_LOGIN_URL; others, and every request on routes without sessions, get 401, with WWW-Authenticate: Bearer on routes without sessions or behind TokenMiddleware. Responses to logged-in users get Cache-Control: no-store unless the handler sets another
a.GuestGuests only: logged-in users are redirected to AUTH_HOME_URL
a.TokenMiddlewareLogs in the user of a Bearer API token; invalid tokens get 401; no token (or another scheme) passes as a guest
a.RequireConfirmedUsers who confirmed their password in the last AUTH_CONFIRM_TTL only: others are sent to AUTH_CONFIRM_URL, to come back after (to the page for GET, else to the page the form was on); API clients and htmx requests get auth.ErrPasswordNotConfirmed (423). After Require

Logging in and out

APIDoes
a.Attempt(ctx, login, password, remember)Checks the password and logs in; auth.ErrInvalidCredentials (401), *auth.ThrottledError (429) past AUTH_THROTTLE attempts a minute per login or account and IP, or AUTH_THROTTLE_IP failures per IP; for a user with two-factor authentication on, the user and auth.ErrTwoFactorRequired (401): the login waits for a code
a.Login(ctx, u, remember)Logs u in: new session ID; with remember, the remember-me cookie. For a user with two-factor authentication on, auth.ErrTwoFactorRequired instead, and a login waiting for a code (10 minutes). For logging in after registration and by other means than a password (it used to skip the code; SignIn, which asked for it, is deprecated)
a.RememberCookie()The remember-me cookie’s name (__Host-anetos_remember, anetos_remember with WithInsecureCookies)
a.LoginSession(s, u)Writes a logged-in session for u into the *session.Session without a request, as Login without remember-me would, without asking for a two-factor code: for tests (anetostest.ActingAs) and tools; auth.ErrDisabled for a disabled user
a.AttemptTwoFactor(ctx, code)Finishes the waiting login with the authenticator app’s code (each used once) or a recovery code (used up); auth.ErrInvalidCode (422), auth.ErrNoPendingLogin (401: none, expired, or the password changed), *auth.ThrottledError past AUTH_THROTTLE a minute or 50 wrong codes a day (UTC) for the user; auth.ErrDisabled
a.TwoFactorPending(ctx)Whether a login waits for a code in the session
a.AttemptCredentials(ctx, login, password)Attempt’s check (its errors, throttling and rehashing) without a session: returns the user, for an API’s login to give a token; auth.ErrDisabled (403); for a user with two-factor authentication on, a *auth.TwoFactorChallenge (401, errors.Is auth.ErrTwoFactorRequired) whose Token the client sends back with a code. The route needs TokenMiddleware or Middleware
a.AttemptTwoFactorChallenge(ctx, challenge, code)Finishes such a login: checks the challenge (10 minutes, until the password or session key changes) and the code as AttemptTwoFactor does (its lock, limits and errors; auth.ErrNoPendingLogin for a bad, expired or outdated challenge) and returns the user; no session. A challenge works again within its 10 minutes, with a new code
a.CheckPassword(ctx, u, password)Checks u’s password with ConfirmPassword’s budget (AUTH_THROTTLE a minute, 50 wrong a day), without a session: for an API, before what pages put behind RequireConfirmed; auth.ErrInvalidCredentials, *auth.ThrottledError
a.ConfirmPassword(ctx, password), a.PasswordConfirmed(ctx)Checks the logged-in user’s password again, which holds for AUTH_CONFIRM_TTL; auth.ErrInvalidCredentials (also without a password); AUTH_THROTTLE tries a minute for the user, from any address, and 50 wrong passwords a day (UTC, shared with ChangePassword); not while impersonating another user. For a user without a password, a login through Login counts. Logging in or out, and impersonating someone, forget it; never for API tokens
a.SupportsRemember()Whether “remember me” is available (Users.RememberToken set)
a.Logout(ctx)Empties the session, removes the cookie, replaces the remember token
auth.User[U](ctx)The logged-in user, and whether there is one
auth.Current[U](ctx)The logged-in user, auth.ErrUnauthenticated, or the load error
auth.Check(ctx)Whether a user is logged in
auth.CurrentID(ctx)The logged-in user’s AuthID, auth.ErrUnauthenticated, or the load error, for code that works with any user type
a.WithUser(ctx, userID, opts...), auth.WithUser(ctx, userID, opts...)A context whose logged-in user is that user (loaded with Users.ByID when asked for; none if it doesn’t exist), for queue jobs and commands working for a user; no session (Attempt, Login and Logout refuse) and no token, unless auth.WithAbilities(abilities) gives it a token’s limits. The function finds the app’s Auth in ctx
auth.Intended(ctx, fallback)The page a guest asked for before logging in, or fallback

Accounts

APIDoes
Users.Disabled, a.Disabled(u)A disabled user is logged out on their next request; Attempt (once the password checks out) and Login return auth.ErrDisabled (403); their remember-me cookies and API tokens stop working; WithUser treats them as a guest
a.ChangePassword(ctx, u, current, new)Changes u’s password (needs Users.SetPassword), logging them out of their other sessions and remember-me cookies (LogoutOthers); auth.ErrInvalidCredentials for a wrong current; a user without a password sets one without current within AUTH_CONFIRM_TTL of logging in (auth.ErrPasswordNotConfirmed after); AUTH_THROTTLE tries a minute, and 50 wrong passwords a day (UTC, shared with ConfirmPassword); not while impersonating someone
a.LogoutOthers(ctx, u)Ends u’s other sessions (with Users.SessionKey), remember-me cookies and password-reset links, keeping the request’s session if it is u’s (with a new session ID, and a new remember-me cookie if it had one)
a.LogoutEverywhere(ctx, u), a.SupportsLogoutEverywhere()Ends every session and remember-me cookie of u by giving them a new session key (Users.SetSessionKey) and remember token; API tokens stay
a.Impersonate(ctx, u)Logs the current user in as u, keeping who they are in the session; not through API tokens, not nested, not for a disabled u (ErrDisabled) or oneself. Each request checks that the impersonator may still log in; Logout ends both (leaving u’s remember-me token alone). The impersonator’s remember-me cookie is removed. Check who may first (rbac.AuthorizeOver)
a.StopImpersonating(ctx)Logs the impersonator back in and returns them; auth.ErrNotImpersonating (409) without impersonation; if they can’t log in any more, logs out and returns why
auth.Impersonator(ctx)The ID of the user impersonating the logged-in one, and whether there is one

Two-factor authentication

TOTP (RFC 6238: six digits, 30 seconds, HMAC-SHA-1) and recovery codes; see Two-factor authentication. Needs Users.TwoFactor and SetTwoFactor.

APIDoes
a.SupportsTwoFactor()Whether two-factor authentication is available
a.TwoFactor(u)auth.TwoFactorStatus{On, Started, RecoveryCodes}; an error if the state can’t be read (APP_KEY changed)
a.StartTwoFactor(ctx, u, account)Stores a new secret, replacing a started setup; returns auth.TwoFactorSetup{Secret, URI} (base32 key, otpauth:// URI with APP_NAME as issuer); auth.ErrTwoFactorOn (409) if on
a.StartedTwoFactor(u, account)The started setup again; auth.ErrTwoFactorOff if none, ErrTwoFactorOn once on
a.ConfirmTwoFactor(ctx, u, code)Turns it on with a current code; returns 8 recovery codes (abcde-fghij), to show once; ends u’s other sessions and remember-me cookies (LogoutOthers); auth.ErrInvalidCode, ErrTwoFactorOff, ErrTwoFactorOn; throttled
a.NewRecoveryCodes(ctx, u)Replaces the recovery codes; auth.ErrTwoFactorOff if off
a.DisableTwoFactor(ctx, u)Turns it off (or drops a started setup)
auth.TwoFactorCode(secret, t)The code an app shows at t, for tests

Tokens

APIDoes
a.PasswordResetToken(u), a.CheckPasswordResetToken(ctx, token)Reset tokens: AUTH_RESET_TTL, until the password or the session key changes; auth.ErrInvalidToken (400)
a.VerificationToken(u, email), a.CheckVerificationToken(ctx, token)Email-verification tokens: AUTH_VERIFY_TTL; returns the user and the address
a.EmailRevertToken(u, old, new), a.CheckEmailRevertToken(ctx, token)Tokens for the link, sent to the old address, that undoes a change of email address: AUTH_REVERT_TTL; returns the user and both addresses
a.CreateToken(ctx, u, name, abilities, ttl)An API token (<id>|<secret>, shown once) and its stored auth.Token; 403 while impersonating another user. Put the route behind RequireConfirmed
a.Tokens(ctx, u), a.RevokeToken(ctx, u, id), a.RevokeAllTokens(ctx, u)A user’s API tokens; delete one, or all
a.RevokeOtherTokens(ctx, u, keep)Deletes u’s API tokens but keep (the request’s, after a password change through the API)
a.ClientLink(path, query)AUTH_CLIENT_URL joined with path and query: the link an API’s emails give to the client app; an error naming the setting when it isn’t set
auth.CurrentToken(ctx), auth.TokenCan(ctx, ability)The request’s API token; whether it (or a session user) may do ability ("*": all)
auth.RequireAbilities(abilities...)Middleware: a token needs every one of the abilities (403 without them, 401 for a guest); a session user may do anything. Its routes’ OpenAPI security lists them as scopes

Authorization

APIDoes
auth.Authorize(ctx, policy, subject)nil, auth.ErrUnauthenticated (401) or auth.ErrForbidden (403); policy is func(context.Context, U, T) bool
auth.AuthorizeUser(ctx, policy)The same for func(context.Context, U) bool
auth.Allows, auth.AllowsUserThe answer as a boolean (false for a guest)
auth.IsDenied(err)Whether err is ErrUnauthenticated or ErrForbidden

Passwords

APIDoes
password.Hash(pw)argon2id hash (19 MiB, 2 passes, 1 thread), as a PHC string; password.ErrTooLong over 1024 bytes
password.Verify(pw, hash)Checks against argon2id or bcrypt ($2a$, $2b$, $2y$) hashes
password.NeedsRehash(hash)bcrypt, or argon2id weaker than the defaults
password.HashWith(pw, params), password.Defaults()Other parameters (at most 256 MiB and 10 passes)
password.IsBcrypt(hash)Whether the hash is bcrypt, which checks only a password’s first 72 bytes
password.Dummy(pw)Spends the time of a check, for unknown users
password.VerifyContext(ctx, pw, hash), password.DummyContext(ctx, pw)The same, giving up with ctx’s error while waiting for a free slot (a few hashes are computed at once)

Social login

APIDoes
social.Google(), social.GitHub(), social.GitHubAt(web, api), social.OIDC(name, issuer)Providers; their Scopes, Title (“Google”, for buttons; OIDC’s defaults to its name) and other fields can be changed
social.Configured(app, providers...)The providers whose SOCIAL_<NAME>_CLIENT_ID and _CLIENT_SECRET are set
social.New(app, a, resolve, providers, opts...)*social.Social[U]; needs APP_URL (https in production); with no providers, its routes answer 404; social.WithHTTPClient, social.WithLogger, social.WithCallbackPath, social.WithHomeURL(path) (where users go without an intended page; default AUTH_HOME_URL)
social.NewWithConfig(a, resolve, baseURL, creds, providers, opts...)Without an app
s.Redirect, s.CallbackHandlers for /auth/{provider}/redirect (?remember=1) and /auth/{provider}/callback
s.Providers(), s.CallbackURL(name)Provider names, in the order given; a provider’s callback URL to register
social.Resolver[U], social.Profilefunc(ctx, Profile) (U, error): finds or creates the user; the profile has Provider, Subject, Email, EmailVerified, Name, AvatarURL, Token
social.NoAccountError{Message}Refuses a login with a message on the login page (social field)
s.Providers(), s.Title(name)The providers’ names, in the order given, and their titles, for login buttons
social.Migrations()The social_accounts table
social.FindLink(ctx, p), social.Link(ctx, p, userID), social.Links(ctx, userID), social.Unlink(ctx, userID, provider)Links between provider accounts and users

Roles and permissions

Package auth/rbac. Concepts: Roles and permissions.

Declaring

APIDoes
rbac.PermissionA string type: const EditPosts rbac.Permission = "posts.edit"; lowercase letters, digits and . _ : -, up to 100 characters; also the API token ability that allows it
rbac.Role{Name, Title, Permissions, Super, Custom}A role; Super has every permission (code only); Custom is set for roles of the database. r.Allows(p), r.DisplayName() (the title, or the name)
rbac.New(app, permissions, roles...)*rbac.Registry, checked (unique names, roles of declared permissions); provided to the app and its contexts; caches grants per operation; adds the commands below; once per app
rbac.NewRegistry(permissions, roles...), rbac.WithRegistry(ctx, reg), rbac.From(ctx)Without an app; rbac.ErrNoRegistry when the context has none
reg.Declare(permissions...)Adds permissions to the registry, for packages that bring their own (the admin); idempotent; call it at setup, before the app serves
rbac.AuthorizeOver(ctx, userID)nil if the logged-in user has every permission userID has in every scope (and a super role wherever they have one), else auth.ErrForbidden: for managing their account
rbac.GivenTo(ctx, userID)The roles and permissions given to a user, as stored (rbac.Given{Scope, Role, Permission}), by scope and name
rbac.RoleCounts(ctx), rbac.Holders(ctx, role, limit)How many users have each role; who has a role, and where (rbac.Holder{UserID, Scope})
reg.Permissions(), reg.Declared(p), reg.Roles(), reg.Role(name)What was declared
rbac.Migrations()The rbac_grants and rbac_roles tables

Scopes

APIDoes
rbac.Scope, rbac.GlobalWhere a grant applies: rbac.Global ("") everywhere, or one scope
rbac.ScopeOf(kind, id)"team:42"; kind is lowercase letters, digits, _ and - (panics otherwise); IDs compare exactly (ABC isn’t abc, on every database); stored scopes are up to 100 bytes (rbac.ErrInvalidScope, 422)
s.Kind(), s.ID(), s.String()"team", "42"; "global" for rbac.Global

Checking the logged-in user

A global grant applies in every scope. For a request logged in with an API token, a permission must also be among the token’s abilities (or the token has *), and role checks are false unless it has *.

APIDoes
rbac.Authorize(ctx, p), rbac.AuthorizeIn(ctx, scope, p)nil, auth.ErrUnauthenticated (401), auth.ErrForbidden (403), or another error (the database; an undeclared permission, 500)
rbac.Can(ctx, p), rbac.CanIn(ctx, scope, p)The answer as a boolean: false for a guest; other errors are logged
rbac.HasRole(ctx, role), rbac.HasRoleIn(ctx, scope, role)Whether the user has the role in scope or globally
rbac.AuthorizeRole(ctx, scope, role)nil if the user may give the role in scope: they have every permission it allows there (super there, with a * token, for a super role); else 401, 403 or rbac.ErrUnknownRole. Compares permissions, not names
rbac.AuthorizeRolesOf(ctx, scope, userID)nil if the user may give every role userID has in exactly scope, so may change or remove them; else 401 or 403
rbac.Require(perms...), rbac.RequireIn(scopeFn, perms...)Middleware: every permission, globally or in scopeFn(r)’s scope; the error of Authorize otherwise. After the auth middleware
rbac.PathScope(kind, param)A scopeFn from a path parameter: PathScope("team", "team") on /teams/{team}; 404 without it
rbac.Current(ctx)The logged-in user’s *rbac.Grants (token limits applied), or auth.ErrUnauthenticated

Any user’s grants

APIDoes
rbac.Of(ctx, userID)The user’s *rbac.Grants, read in one query (two with roles of the database) once per operation (request, job, listener, task, tool call)
g.Can(p), g.CanIn(scope, p)Whether a grant in scope, or a global one, allows p
g.HasRole(role), g.HasRoleIn(scope, role)Whether the user has the role in scope or globally (declared or stored roles only; none for a token without *)
g.Roles(scope)The roles assigned in exactly scope, by name (the same rules)
g.Permissions(scope)The permissions allowed in scope (with global grants), in declaration order
g.Scopes(kind)The scopes of kind where the user has a role or a declared permission, sorted: their teams

Changing grants

APIDoes
rbac.Assign(ctx, userID, scope, roles...)Adds roles (declared, or of the database: rbac.ErrUnknownRole, 422); user IDs are up to 100 bytes
rbac.Unassign(ctx, userID, scope, roles...)Takes roles away in exactly scope
rbac.Sync(ctx, userID, scope, roles...)Makes roles the user’s only roles in scope (none: removes them all)
rbac.Grant(ctx, userID, scope, perms...), rbac.Revoke(…)Single permissions without a role (rbac.ErrUnknownPermission, 422)
rbac.RemoveUser(ctx, userID)Every grant of the user, in every scope
rbac.RemoveScope(ctx, scope)Every grant in the scope (not rbac.Global)
rbac.Assignments(ctx, scope)[]rbac.Assignment{UserID, Role} in exactly scope, by user and role: its members
rbac.UsersWith(ctx, scope, p)IDs of the users allowed p in scope (with global grants), sorted

Roles of the database

APIDoes
rbac.CreateRole(ctx, role)Stores a role of declared permissions; rbac.ErrRoleExists (409), rbac.ErrInvalidRole (422: invalid name or title, a code role’s name, super); users still holding a removed code role of the name lose it
rbac.UpdateRole(ctx, role)Replaces its title and permissions; rbac.ErrUnknownRole, rbac.ErrInvalidRole for a code role
rbac.DeleteRole(ctx, name)Deletes it and its assignments
rbac.Roles(ctx), rbac.FindRole(ctx, name)Every role, code’s first; one role, code’s or the database’s

Commands

CommandDoes
rbac:rolesThe roles, where they’re defined, their users and permissions; warns of assigned roles that are neither declared nor stored, and of stored roles a code role replaces
rbac:user <user-id>A user’s roles and permissions by scope
rbac:assign [--scope=team:42] <user-id> <role>Gives a role, globally without --scope
rbac:unassign [--scope=team:42] <user-id> <role>Takes it away