Skip to content

Latest commit

 

History

History
309 lines (266 loc) · 76.3 KB

README.md

File metadata and controls

309 lines (266 loc) · 76.3 KB

github.com/ubgo/auth/plugin/oauth

Lets people sign in with Google, GitHub, Apple or any OpenID Connect issuer (Okta, Auth0, Keycloak, Entra ID, Zitadel), link those accounts to an existing user, sign in from a native app with the provider's ID token, sign out at the provider too, and optionally keep the provider's tokens for calling its API later.

Install

go get github.com/ubgo/auth

The package is part of the core module github.com/ubgo/auth. It adds no dependency beyond the core's own (github.com/ubgo/sqlb, golang.org/x/crypto): provider calls use net/http and encoding/json from the standard library.

Wire it

From examples/oauth:

a, err := auth.New(
	auth.WithDB(db, sqlb.SQLiteDialect{}),
	auth.WithBaseURL(baseURL),
	auth.WithPlugins(
		email.New(email.Login(), email.Recover(), email.WithMailer(m)),
		password.New(),
		oauth.New(oauth.WithProviders(oauth.GitHub(os.Getenv("GITHUB_CLIENT_ID"), os.Getenv("GITHUB_CLIENT_SECRET")))),
	),
)
// ...
mux.Handle("/auth/", authhttp.Handler(a, authhttp.Prefix("/auth")))

The plugin works alone (it is a sign-in method by itself), but with the email plugin a provider that vouches for a verified address that is already a verified identity signs in to that account instead of creating a second one. Register BaseURL + "/auth/oauth/<provider>/callback" as the redirect URI at each provider.

auth.New fails when:

Condition Error
No provider passed ErrNoProviders: "oauth: no providers"
A provider name does not match auth.KindNamePattern (^[a-z][a-z0-9_]{0,30}$) "oauth: provider name %q must match ..."
Neither auth.WithBaseURL nor oauth.CallbackURL is set ErrNoCallbackURL: "oauth: callback URLs need auth.WithBaseURL or oauth.CallbackURL"
StoreTokens got a key that is not auth.SealKeySize (32) bytes, or no key while auth.WithSecret is not set ErrBadTokenKey: "oauth: StoreTokens needs a 32-byte key"
An *OAuth2 lacks AuthURL, TokenURL (unless GetToken replaces the exchange), ClientID or a profile source (FetchProfile, or IDToken.ProfileFromToken), names an unknown TokenAuth, or is a PublicClient with a ClientSecret or ClientSecretFunc ErrProviderIncomplete: "oauth: a provider needs AuthURL, TokenURL (or GetToken), ClientID, FetchProfile (or IDToken.ProfileFromToken) and a known TokenAuth (no secret for a PublicClient)"
An *OIDCProvider has a Fallback with some endpoint set but no AuthURL, TokenURL or UserInfoURL ErrFallbackIncomplete
AllowProviderInitiated or RestartProviderInitiated names a provider that is not configured, both name the same one, or AllowProviderInitiated names an *OAuth2 without an IDToken key set or a custom provider that is not an InitiatedExchanger ErrProviderInitiatedConfig
SkipBrokenProviders is set and every provider was left out ErrAllProvidersBroken, wrapping each provider's reason
An IDTokenConfig has a JWKSURL but no Issuers, or ProfileFromToken without a JWKSURL; an *OIDCProvider with a hand-set IDToken.JWKSURL and no Issuers ErrIDTokenConfig: "oauth: IDToken needs JWKSURL and Issuers (ProfileFromToken needs both)"
ErrorURL is not a path on this site or a trusted origin ErrBadReturnTo (from Init)
Neither auth.WithBaseURL nor oauth.PostLogoutURL is set ErrNoCallbackURL

Built-in providers

The library reads no environment variables; the names below are the ones examples/oauth uses.

Constructor Route segment Needs Scopes Endpoints Example env
oauth.Google(clientID, clientSecret) google OAuth client id and secret from Google Cloud openid email profile GoogleAuthURL, GoogleTokenURL, GoogleUserInfoURL GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
oauth.GitHub(clientID, clientSecret) github OAuth app client id and secret read:user user:email GitHubAuthURL, GitHubTokenURL, GitHubAPIURL (/user, /user/emails) GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET
oauth.OIDC(name, issuer, clientID, clientSecret) name (you choose, e.g. okta) Issuer URL plus client id and secret openid email profile Discovered from issuer + "/.well-known/openid-configuration" at the first start; jwks_uri and end_session_endpoint too OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET
oauth.Apple(clientID, secret, audiences...) apple The Services ID as client id; secret from oauth.AppleClientSecret(teamID, clientID, keyID, oauth.ParseAppleKey(p8)); the iOS bundle ids as extra audiences none; oauth.AppleWithEmail (same arguments) requests email name and takes Apple's form post (see below) AppleAuthURL, AppleTokenURL, AppleJWKSURL, issuer AppleIssuer APPLE_CLIENT_ID, APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_KEY_FILE
oauth.Microsoft(tenant, clientID, clientSecret) microsoft Entra ID app registration; tenant is a tenant id or domain, or common, organizations, consumers openid email profile MicrosoftAuthURLFormat, MicrosoftTokenURLFormat, MicrosoftUserInfoURL; subject oid; ID tokens for a single tenant MICROSOFT_TENANT, MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET
oauth.Discord, oauth.Facebook, oauth.Spotify, oauth.Dropbox, oauth.Atlassian, oauth.Kakao, oauth.Naver, oauth.Kick, oauth.Linear, oauth.Polar, oauth.Vercel, oauth.Patreon, oauth.Gumroad, oauth.HubSpot, oauth.Yandex (clientID, clientSecret) the lowercase name OAuth client id and secret from the provider the provider's defaults (in each constructor's doc) Exported <Name>AuthURL, <Name>TokenURL, <Name>ProfileURL constants; the secret in the form —
oauth.X, oauth.Zoom, oauth.Figma, oauth.Cloudflare (clientID, clientSecret); oauth.Reddit(clientID, clientSecret, userAgent); oauth.PayPal(clientID, clientSecret, sandbox) x, zoom, figma, cloudflare, reddit, paypal As above; Reddit also needs a User-Agent naming the app the provider's defaults As above, with TokenAuth: ClientSecretBasic because these token endpoints take HTTP Basic; PayPal's sandbox switches to the sandbox endpoints —
oauth.Slack, oauth.LinkedIn, oauth.Twitch, oauth.LINE, oauth.HuggingFace, oauth.Roblox, oauth.Paybin, oauth.Railway (clientID, clientSecret); oauth.GitLab, oauth.Salesforce, oauth.Okta, oauth.Keycloak, oauth.Zitadel (issuer, clientID, clientSecret); oauth.Auth0(domain, …); oauth.Cognito(region, userPoolID, …) the lowercase name Client id and secret; the issuer where it is yours openid email profile (Roblox openid profile; Twitch adds user:read:email and the claims request its userinfo needs) oauth.OIDC over the issuer constants SlackIssuer, LinkedInIssuer, GitLabIssuer, TwitchIssuer, LINEIssuer, HuggingFaceIssuer, RobloxIssuer, PaybinIssuer, RailwayIssuer, SalesforceIssuer / SalesforceSandboxIssuer —
oauth.TikTok(clientKey, clientSecret), oauth.Notion(clientID, clientSecret), oauth.VK(clientID, clientSecret), oauth.WeChat(appID, appSecret, lang) tiktok, notion, vk, wechat TikTok: the client key (sent as client_key) and secret of a Login Kit for Web app. Notion: a public integration's OAuth client id and secret. VK ID: the app id and secret. WeChat: a website app's AppID and AppSecret, and the QR page language (WeChatLangCN, the default for "", or WeChatLangEN) TikTok user.info.basic (comma-joined); Notion none (owner=user); VK email phone; WeChat snsapi_login TikTokAuthURL, TikTokTokenURL, TikTokUserInfoURL, TikTokRevokeURL; NotionAuthURL, NotionTokenURL (JSON body, HTTP Basic), NotionMeURL with Notion-Version NotionVersion; VKAuthURL, VKTokenURL (with the callback's device_id and state), VKUserInfoURL (posted form); WeChatAuthURL (appid, #wechat_redirect), WeChatTokenURL and WeChatRefreshURL (GETs with appid and secret), WeChatUserInfoURL TIKTOK_CLIENT_KEY, NOTION_CLIENT_ID, VK_CLIENT_ID, WECHAT_APP_ID and their secrets
oauth.Dub(clientID, clientSecret), oauth.Instagram(appID, appSecret), oauth.Snapchat(clientID, clientSecret), oauth.Zoho(region, clientID, clientSecret) dub, instagram, snapchat, zoho Dub: an OAuth app's client id and secret. Instagram: the app id and secret of a Meta app with Instagram API with Instagram Login (professional accounts only). Snapchat: a Login Kit app's OAuth client id and secret. Zoho: a client from the Zoho API console and its data centre, a oauth.ZohoRegion (ZohoUS, ZohoEU, ZohoIndia, ZohoAustralia, ZohoJapan, ZohoUK, ZohoCanada, ZohoSaudi, ZohoChina; ZohoRegionValues lists them) Dub user.read; Instagram instagram_business_basic (comma-joined); Snapchat user.external_id user.display_name user.bitmoji.avatar as full URLs under SnapchatScopePrefix; Zoho openid email profile DubAuthURL, DubTokenURL, DubUserInfoURL; InstagramAuthURL, InstagramTokenURL, InstagramMeURL; SnapchatAuthURL, SnapchatTokenURL (HTTP Basic), SnapchatRevokeURL, SnapchatMeURL (GraphQL {me{externalId displayName bitmoji{avatar}}}); Zoho discovered from the region's issuer DUB_CLIENT_ID, INSTAGRAM_APP_ID, SNAPCHAT_CLIENT_ID, ZOHO_CLIENT_ID and their secrets

Apple has no userinfo endpoint, so its profile comes from the ID token the token endpoint returns, verified against Apple's keys (IDToken.ProfileFromToken); its client secret is a signed assertion, renewed every day by AppleClientSecret. oauth.Apple requests no scopes, so its web flow yields the subject alone; the native flow (the id-token route) carries the email when the person shared it. oauth.AppleWithEmail requests email and name, which Apple answers by response_mode=form_post: a cross-site POST to the callback URL, which carries no SameSite=Lax flow cookie. The plugin therefore serves POST at every form-post provider's callback route as a relay that answers a redirect to the GET callback with the same code, state and user fields; the browser follows it as a top-level GET, the one cross-site request the flow cookie travels with, and the GET callback checks the state as always. The email comes from the ID token (a private relay address when the person hid theirs); the name comes from the user field Apple sends once, on first consent, read by oauth.ApplePostedUser into Profile.Name (and into Profile.Email, unverified, only when the token had none). Register the same callback URL at Apple either way.

The presets' shapes follow each provider's documented API, pinned by fixture tests (TestPresets_ProfileReaders), not by calls to the live provider. A preset marks the email verified only when the provider's answer says so: Discord (verified), Dropbox, Atlassian, Kakao, Patreon, Zoom (verified), X (a confirmed address) and every OpenID Connect issuer with email_verified do; Facebook, Spotify, Figma, Naver, Kick, Linear, Cloudflare, Gumroad, HubSpot, Yandex and Microsoft (Graph's userinfo has no flag) do not, so their addresses never link to an existing user by themselves. TrustedProviders("facebook", "linear") trusts the ones you choose. Reddit returns no email. oauth.Presets lists every route segment. Google One Tap and the Google mobile SDKs: set g.IDToken = oauth.GoogleIDTokens(audiences...) on oauth.Google (keys at GoogleJWKSURL, both Google issuers), or oauth.GoogleIDTokensFor(hostedDomain, …) to refuse tokens outside one Workspace domain.

TikTok, Notion and WeChat run without PKCE (NoPKCE, below), because their web flows document none: the state stays single use and bound to the browser, and the client secret still guards the exchange, but a code stolen in transit could be injected into another browser's callback. VK ID runs PKCE. TikTok and WeChat send no email, so their users are created with no identity; Notion's and VK's addresses are unverified. WeChat's token endpoints are GETs that carry the app secret in the query string, as WeChat documents them; keep that host out of any proxy that logs URLs. VK ID's refresh grant also needs the device_id, which the plugin does not keep after the callback, so Tokens cannot refresh a VK token: request a fresh sign-in when it expires, or implement oauth.Refresher on a provider of your own. Sources: each provider's own documentation, read on 2026-10-06 (TikTok's through the Internet Archive, since developers.tiktok.com answers 503); the shapes are pinned by TestTikTok_*, TestNotion_*, TestVK_* and TestWeChat_*, not by live calls.

Dub, Instagram, Snapchat and Zoho were added on 2026-10-08. Dub and Snapchat run PKCE; Instagram runs without it (NoPKCE), as its documentation has none. None of Dub, Instagram or Snapchat sends an email, so their users are created with no identity; these presets do not invent an address such as <id>@instagram.com or <id>@snapchat.com, because a made-up address would look like a real one. Instagram's token answer is not RFC 6749 (documented wrapped in a data array, also seen flat), so the preset reads either; the token is the one-hour short-lived one (InstagramTokenLifetime) and does not refresh, and force_reauth is an allowed per-request parameter. Dub's userinfo carries the authorized workspace, kept in Profile.Claims["workspace"]. Zoho signs in the users of the one data centre the client was registered in. Sources: each provider's documentation, read on 2026-10-08; pinned by TestDub_*, TestInstagram_*, TestSnapchat_*, TestZohoRegions and TestPresetsP3_Constructors, not by live calls.

Any other provider: fill an *oauth.OAuth2 (ID, ClientID, ClientSecret, AuthURL, TokenURL, Scopes, FetchProfile), or implement the oauth.Provider interface (Name, AuthCodeURL, Exchange). Implementing oauth.Refresher enables token refresh in Tokens; implementing oauth.Discoverer makes the start operation call Discover first; implementing oauth.IDTokenVerifier gives the provider an id-token route and oauth.Logouter a logout route; oauth.ProfileFetcher lets Profile read the provider's profile with stored tokens, oauth.Revoker lets unlink revoke them, and oauth.IssuerChecker makes the callback require the RFC 9207 iss. *OAuth2 and *OIDCProvider implement all seven, plus oauth.Labeler (the display name), oauth.Loader (what SkipBrokenProviders loads at start) and oauth.InitiatedExchanger (provider-initiated sign-in). Prove a provider of your own with the conformance kit oauthtest.Run (oauthtest); to reuse a goth provider instead, wrap it with authgoth.Wrap from the separate module contrib/goth. oauth.FormPoster (*OAuth2 with FormPost) gets the POST relay at its callback route and oauth.PostedProfile (*OAuth2 with PostedUser) is handed the callback's user field. GitHub's email comes from /user/emails, the address GitHub marks primary, with GitHub's own verified flag. Set TokenAuth, AuthParams, TokenParams, OptionalScopes, TokenLifetime, IDToken, EndSessionURL and ClientSecretFunc on an *oauth.OAuth2 as the provider needs; a Provider of your own implements oauth.ParamsProvider too to accept prompt, loginHint and extra scopes per request.

A provider whose authorization URL depends on the request that starts the flow implements oauth.RequestAuthURLer: start then calls AuthCodeURLForRequest(ctx, state, challenge, redirectURI, params) with the request's context instead of AuthCodeURL, so the provider can read a header or the host with auth.RequestHeader and auth.RequestHost. Request parameters still need a ParamsProvider. plugin/oauthproxy uses it for its per-request skip header.

Options

Option What it does Default
WithProviders(ps ...Provider) Adds providers; one start and one callback operation each none (required)
WithHTTPClient(hc *http.Client) Client for every provider call. Provider calls never follow a redirect (ErrRedirectRefused, logged; the flow fails with oauth.provider_failed), so a misconfigured or hostile endpoint cannot bounce the server to an internal address; a client with no CheckRedirect of its own is used as a copy with that policy &http.Client{Timeout: DefaultHTTPTimeout} (10s), refusing redirects
WithStateTTL(d time.Duration) How long a user may spend at the provider before the callback is refused DefaultStateTTL (10 minutes)
StoreTokensWith(s) StoreTokens with the tokens sealed by an auth.Sealer (Vault transit, AWS KMS) instead of an in-memory key; wins over auth.WithSealer, loses to a StoreTokens key. A seal error fails the sign-in; an open error is returned by Tokens off
StoreTokens(key ...[]byte) Keeps each account's access and refresh token, sealed with AES-256-GCM under key, or with no key under the app's auth.WithSealer when set, else the keys derived from auth.WithSecret (label auth.KeyLabelOAuthTokens, current secret first, so a rotated secret still opens old tokens); read back with Tokens off: provider tokens are never stored
CallbackURL(fn func(provider string) string) The redirect URI sent to each provider BaseURL + DefaultMountPrefix + "/oauth/<provider>/callback" (DefaultMountPrefix is /auth)
NoSignUp(providers ...string) Callbacks never create a user (for the named providers, or all when none is named): a linked account signs in, a verified address matching a verified identity links and signs in, a signed-in user may link; anything else is ErrSignUpDisabled off: strangers get an account
RequireVerifiedEmail() A sign-in or sign-up whose profile has no email or an unverified one is ErrEmailUnverified; link flows are unaffected off: an unverified address creates an unverified identity and signs in
RequireEmail() A sign-in or sign-up whose profile has no email at all is ErrEmailNotFound (oauth.email_not_found), before anything is written; an unverified address is admitted; link flows are unaffected off: a provider account without an email creates a user with no identity
VerifyEmailBeforeSignIn() The user is created or resolved as usual, but no session is issued while the user has no verified email; the browser lands on the error page (errorTo, ErrorURL, auth.WithErrorURL, else the landing page) with ?error=oauth.email_not_verified and the result has emailVerificationRequired: true; the id-token and provider-initiated routes are held the same way; no email at all is ErrEmailNotFound. The person verifies the address with plugin/email's public resend and verify routes and signs in again off
AllowUnlinkingAll() Unlink may remove the user's last sign-in method; the user can then come back only through account recovery off: the last method is auth.last_sign_in_method
LinkUnverifiedLocalEmail() A verified provider address also links to a local account holding it unverified. Escape hatch: Init logs WarnLinkUnverifiedLocal at every start, because anyone can pre-register a victim's address with a password of their own and the victim's later provider sign-in lands in that account (pre-hijacking) off: such a link is oauth.account_exists
StateInCookie() The state, PKCE verifier and flow data are sealed into the flow cookie (key derived from auth.WithSecret under auth.KeyLabelOAuthState), so a start writes no row; bound to the provider and the state TTL. Needs auth.WithSecret and refuses SkipStateCookieCheck (ErrStateCookieKey) off: a verification row
UpdateProfileOnSignIn() Every sign-in and link copies the profile's name and image onto the user (name cut to auth.MaxNameLength; an image only when https:// and within auth.MaxImageLength) off: the profile fills the user at creation only
NoImplicitLinking() The automatic link by verified email is off: a matching address is ErrAccountExists even when both sides are verified; people link from settings off: both-sides-verified matches link automatically
TrustedProviders(providers ...string) The named providers' addresses count as verified for linking even when the profile does not say so; the local identity must still be verified. Only for a provider you know verifies addresses: otherwise it is an account takeover none
RequireSameEmailOnLink() A link flow whose provider address is not one of the signed-in user's identities is ErrEmailMismatch off: a signed-in user may link any provider account
ErrorURL(path) A failed callback redirects the browser to this page on this site with the error code in the query (?error=oauth.denied, appended by the core's Call.RedirectOnError); a request may name another page with StartRequest.ErrorTo off: a failed callback answers the error as JSON
PostLogoutURL(fn func(provider string) string) The post_logout_redirect_uri sent with a provider logout; register it at the provider. A logout request's own returnTo replaces it for that request the base URL
ExplicitSignUp(providers ...string) A callback or id-token sign-in creates a user only when the request asked (signUp=true on start, "signUp":true on the id-token route); otherwise a stranger is ErrSignUpNotRequested. Linked accounts, verified-email matches and link flows are unaffected; NoSignUp wins where both apply off: a stranger signs up implicitly
ValidateProfile(fn ProfileHook) Runs before a callback or id-token sign-in writes anything, with the ProfileEvent: provider, profile (Claims included), the action (sign_in, sign_up, link), the user id (empty for a sign-up), the start's data, ProviderInitiated for a sign-in the provider started, and Reauthentication for a signed-in user confirming who they are with a linked account (the action is then sign_in, so a sign-in rule holds it too; it also runs on that callback and on an ID-token re-authentication). An *auth.Error it returns is answered as it is; any other error is logged and answered as ErrProfileRefused. Several run in order none
SkipBrokenProviders() A provider whose configuration fails its check, or whose discovery document or key set cannot be loaded, is logged at Error and left out (its routes, the providers list, every lookup by name); the others keep working. auth.New then loads every discovery document and key set at once, in parallel, through the Loader interface (*OAuth2 and *OIDCProvider implement it); a Fallback in use counts as loaded. A skipped provider comes back when the app restarts with it fixed. Every provider broken is still ErrAllProvidersBroken off: a bad configuration fails auth.New, and an unreachable issuer fails the flow that needed it (oauth.provider_failed)
SkipStateCookieCheck() A callback is accepted without the flow cookie matching its state; the state is still required, single use, and checked against its stored row, provider and expiry. It opens login CSRF: an attacker starts a flow, signs in at the provider as themself and sends the victim the callback URL, and the victim is signed in to the attacker's account. Init logs a warning at every start while it is on. Prefer authhttp's CookieDomain or the desktop hand-off for a callback the flow cookie cannot reach off: the flow cookie must match
AllowProviderInitiated(provider, more...) The named providers may start a sign-in themselves (a tile on an Okta, Entra ID or Workspace dashboard): a callback with a code and no state is exchanged without PKCE, and accepted only when the token response's ID token verifies (signature, issuer, audience, lifetime), carries no nonce, and names the profile's subject. The person is signed in only as the user already linked to that subject, or as a new user (NoSignUp, ExplicitSignUp, RequireVerifiedEmail and the hooks still apply, and ProfileEvent.ProviderInitiated is true); a matching address is ErrAccountExists, never a link; a signed-in browser is signed out first; it lands on /. Only for providers that verify ID tokens. Login forgery is the accepted risk: anyone holding a code for their own account can sign someone else's browser in as themselves off for every provider
RestartProviderInitiated(provider, more...) For the named providers, a callback with a code and no state drops the code unread and answers an ordinary start in its place (fresh state bound to the browser, PKCE), so the browser returns to the provider, which signs a person who is signed in there straight through, and the next callback is checked as usual; it lands on /. No login-forgery risk, works for every provider, costs one more round trip. A provider may not be named by both modes off for every provider
OnResolved(fn ResolvedHook) Runs after the flow resolved its user, in the same transaction and before the session is issued, with the ResolvedEvent (the ProfileEvent plus Created and Linked); an error rolls the user back. For writing provider claims into the app's own columns with auth.SetUserColumn none
(always) Once a callback, id-token or provider-initiated sign-in resolved its user, or a re-authentication callback checked its account, the call is annotated (auth.Call.Annotate) under AnnotationAction (oauth.action) with an AccountAction: sign_in, sign_up, link (a signed-in user linked it) link_email (linked because the verified addresses matched) or reauthenticate (a re-authentication callback or ID token: nothing signed in, created or linked), so an After or Finally hook, plugin/audit's included, records what happened with no app wiring
WithIDTokenReplayGuard(g IDTokenReplayGuard) Replaces the guard that accepts each ID token once (native sign-in and ID-token re-authentication). Claim(ctx, IDTokenClaim) gets the claim: the hex SHA-256 of the token's signed part (header and payload, never the signature, which ES256 lets be spelled twice), the provider, and the token's exp plus 30 seconds; it returns nil the first time and ErrIDTokenReplayed after, exactly one of concurrent claims winning; any other error fails the request. IDTokenReplayGuardFunc adapts a function. nil is refused a verification row of purpose oauth.id_token_claim in the core's verification store, inside the operation's transaction, swept by auth sweep; auth.New refuses (ErrIDTokenReplayConfig) a store that cannot refuse a duplicate (auth.ExclusiveVerificationStore: the SQL table, memory, contrib/redis)
AllowIDTokenReplay() Turns the replay check off by name: a captured ID token signs in, or re-authenticates its user, until it expires. Logs WarnIDTokenReplayAllowed at start. Not with WithIDTokenReplayGuard (ErrIDTokenReplayConfig) off: every token is accepted once
WithServerContext(fn ServerContextFunc) fn(ctx, call, provider) runs at every start and id-token sign-in and returns server-set values (a tenant id the request resolved), stored with the state where no client can set them and handed back in CallbackResult.ServerContext (Go only, never in the JSON) and ProfileEvent.ServerContext; several run in order, a later key wins; an error refuses the start; at most 1024 characters as JSON (ErrServerContextTooLong) none
ExposeAccessTokens() Adds POST /oauth/access-token: the signed-in user's own access token, refreshed when due, with its expiry, granted scopes and ID token, never the refresh token. The risk: it moves a bearer credential for another service into the browser, where any script on the app's origin (one XSS) can read it and call the provider as the user until it expires; turn it on only when the page itself must call the provider. Needs StoreTokens (ErrExposeNeedsStoreTokens) off: provider tokens reach Go code only (Tokens)

Per-provider fields on *oauth.OAuth2 (and the same names on *oauth.OIDCProvider, copied onto the discovered endpoints):

Field What it does Default
TokenAuth How the token endpoint is authenticated to: ClientSecretPost (secret in the form), ClientSecretBasic (HTTP Basic, both halves form-encoded per RFC 6749 2.3.1), PublicClient (client_id only, PKCE alone; a ClientSecret with it fails auth.New), PrivateKeyJWT (an RFC 7523 assertion from ClientAssertion; a ClientSecret with it fails auth.New) ClientSecretPost
ClientAssertion func(ctx, tokenURL) (string, error) Signs the client assertion for PrivateKeyJWT: oauth.ClientAssertion(clientID, kid, key) signs ES256 with a P-256 key or RS256 with an RSA key, iss and sub the client id, aud the token endpoint, a fresh jti, valid 5 minutes. Required with PrivateKeyJWT, refused with any other TokenAuth (ErrAssertionConfig) none
FetchProfileFromTokens func(ctx, hc, TokenSet) (Profile, error) Reads the profile from the whole token set, TokenSet.Raw (the token endpoint's JSON) included, for a provider whose profile call needs more than the access token; wins over FetchProfile none
RefreshParams url.Values Added to refresh requests only, on top of TokenParams; the grant's own keys are ignored none
AuthorizationIssuer string The RFC 9207 iss every callback must carry; a callback without it or with another is ErrStateInvalid. Filled on an *OIDCProvider when discovery publishes authorization_response_iss_parameter_supported none: iss is not checked
RevokeURL string The RFC 7009 revocation endpoint; unlink revokes the stored tokens there (the refresh token when there is one, else the access token), best effort and logged. Discovered (revocation_endpoint) on an *OIDCProvider none: nothing is revoked
AuthParams url.Values Added to every authorization URL (prompt, access_type, hd, display, …); the protocol's own keys (state, client_id, redirect_uri, response_type, scope, code_challenge, code_challenge_method) are ignored none
TokenParams url.Values Added to every token and refresh request; the grant's own keys (grant_type, code, redirect_uri, code_verifier, refresh_token, client_id, client_secret) are ignored none
OptionalScopes []string Scopes a start may add through StartRequest.Scopes, for incremental authorization; any other requested scope is ErrBadScope none
OptionalParams []string Authorization parameters a start may set through StartRequest.Params (display, ui_locales, acr_values, …); any other is ErrBadParam, and the protocol's own (state, redirect_uri, …) never pass none
TokenLifetime time.Duration Access-token lifetime assumed when the token response has no expires_in, so Tokens can refresh in time 0: expiry unknown, no refresh
IDToken IDTokenConfig JWKSURL and Issuers make the provider accept ID tokens on its id-token route; Audiences are accepted aud values besides ClientID (an iOS bundle id); ProfileFromToken reads the profile from the token response's id_token instead of FetchProfile; RequireNonce refuses a token without a nonce claim; HostedDomain refuses a token whose Google hd claim is another Workspace domain. On an *OIDCProvider, JWKSURL and Issuers come from discovery when left empty zero: no ID tokens
EndSessionURL string The provider's RP-initiated logout endpoint, for the logout route; discovered on an *OIDCProvider none: logout answers ErrLogoutUnsupported
ClientSecretFunc func(ctx) (string, error) Computes the client secret per token request, for a provider whose secret is a signed assertion (AppleClientSecret) none: ClientSecret is sent
Headers http.Header Added to every token, refresh and revocation request (a User-Agent naming the app, an API version header); Authorization and Content-Type are ignored, so a header can never replace the credentials or mislabel the body. On an *OIDCProvider, DiscoveryHeaders go on the discovery request instead (Authorization ignored there too: the document is public) none
FormPost bool Sends response_mode=form_post; the provider's answer arrives as a POST at the callback route, which the plugin relays into the GET callback (see Apple above). AuthParams cannot set response_mode off: the answer is a GET query
PostedUser func(raw string, p *Profile) Reads the user field a form-post callback carries into the profile after the exchange (oauth.ApplePostedUser); the field comes from the browser, so a reader must never mark an address verified from it none: the field is ignored
GetToken func(ctx, code, verifier, redirectURI string) (TokenSet, error) Replaces the built-in code exchange, for a token endpoint that is not RFC 6749 (a GET, a JSON body): it gets the callback's code, the flow's PKCE verifier ("" on a provider-initiated sign-in) and the redirect URI. The state, PKCE, the profile read from the returned tokens, linking and the session stay the plugin's. Its error comes out of Exchange unchanged and the callback answers oauth.provider_failed, the reason logged; a set without an access token is a failed exchange; TokenLifetime fills a zero expiry. TokenURL is then needed only for Refresh none: the plugin posts the grant to TokenURL
DisplayName string The provider's name for people, listed by GET /oauth/providers for a sign-in page's buttons (Label() returns it, or the id when empty; a custom provider implements Labeler). Every preset sets one: Google, GitHub, Hugging Face, Amazon Cognito, … the id
NoPKCE bool Per provider, never global: no code_challenge on the authorization URL and no code_verifier at the exchange, for a provider whose web flow has none and might refuse it (the TikTok, Notion and WeChat presets set it). The state stays single use and browser-bound and the secret still guards the exchange; what is lost is RFC 7636's defence against a code stolen in transit and injected into another browser's callback. Refused with PublicClient (ErrPublicClientPKCE), where PKCE is all that ties the code to the client off: PKCE S256 on every flow
ClientIDParam, ClientSecretParam string The names the client id and secret travel under on the authorization URL and in the token, refresh and revocation forms (TikTok client_key; WeChat appid and secret) client_id, client_secret
ScopeSeparator string, AuthURLFragment string How scopes are joined in the scope parameter (TikTok and WeChat take a comma), and a #fragment the authorization URL must end with (WeChat's wechat_redirect) a space; no fragment
CallbackParams []CallbackParam Callback query parameters the token request carries too: CallbackParamDeviceID (VK ID's device_id) and CallbackParamState; any other is ErrCallbackParam. A provider of your own reads the same values with oauth.CallbackValuesOf(ctx) in its Exchange (authgate sets them too) none: the RFC 6749 exchange
RefreshCallbackParams []CallbackParam Callback values the refresh grant needs again (VK ID's device_id): the exchange puts them in TokenSet.RefreshParams, StoreTokens keeps them sealed in refresh_params_sealed (migration 0004_account_refresh_params), and the plugin sends them through ParamRefresher.RefreshWithParams on every refresh none; oauth.VK sets device_id

On an *oauth.OIDCProvider only:

Field What it does Default
Fallback Endpoints Static endpoints (AuthURL, TokenURL, UserInfoURL required; JWKSURL, EndSessionURL, RevokeURL, IssParameterSupported optional) used ONLY while the discovery document cannot be fetched: a transport error, a status other than 2xx, or a body that is not JSON. Each use is logged at Warn, and discovery is tried again after one minute. A document that arrives but names another issuer or lacks an endpoint is still refused: the issuer answered, and what it said is wrong none: a failed discovery fails that flow with oauth.provider_failed
Logger *slog.Logger Receives the fallback warning; the plugin sets the core's logger when it is nil slog.Default() outside the plugin

oauth.GoogleProfileFor(url, hostedDomain) is GoogleProfile restricted to one Google Workspace domain: a userinfo whose hd claim differs is refused (ErrHostedDomain, seen by the user as oauth.provider_failed). The hd authorization parameter is only a hint; this is the enforcement. oauth.UserInfoProfile(url, subjectClaim) reads any OpenID-shaped userinfo answer and takes another claim as the subject (oid for Entra ID, user_id for PayPal); OIDCProvider.SubjectClaim does the same for a discovered issuer. Every built-in profile reader fills Profile.Claims with the raw answer, so a hook can read a provider-specific field.

oauth.MicrosoftPhoto(fetch, size) wraps a Microsoft FetchProfile so the profile image is the person's Graph photo (/me/photos/<size>x<size>/$value, MicrosoftPhotoURLFormat) as a data: URL; size is one of MicrosoftPhotoSizes (48 to 648, else ErrPhotoSize). A missing or unreadable photo, or one longer than MaxPhotoDataURL characters (the image column on MySQL), leaves the image as it was and never fails the sign-in; in practice the 48 and 64 sizes fit. Not wrapping it, the default, fetches no photo.

Routes and Go API

Paths are under the mount prefix (/auth above). A Query is served as GET, a Mutation as POST.

Route Go API Requirement Rate limit
GET /oauth/<provider>/start?returnTo=/path&link=true operation oauth.StartEndpoint(provider) (oauth.<provider>-start); (*Plugin).Start(ctx, provider, StartRequest) from Go, with ctx carrying the request whose response gets the flow cookie Public (link=true, LinkFlag, needs a signed-in user) 30 per IP per minute (startIPLimit, startIPWindow)
GET /oauth/<provider>/start?prompt=consent&loginHint=a%40b.co&scopes=calendar+drive the same operation Public; prompt, loginHint and scopes (space-separated, each in the provider's OptionalScopes) need a ParamsProvider, which *OAuth2 and *OIDCProvider are same
GET /oauth/<provider>/start?params=display%3Dpopup the same operation Public; params is a query string of further parameters, each named in the provider's OptionalParams (OptionalParamList, the ParamsAllowLister interface), else oauth.bad_param
GET /oauth/<provider>/start?data=ref%3D42&errorTo=/oops the same operation Public; data (at most 1024 characters) comes back in CallbackResult.Data; errorTo is a path on this site a failed callback redirects to same
GET /oauth/<provider>/start?newUserTo=/welcome&signUp=true the same operation Public; newUserTo is where a callback that created the user lands instead of returnTo (same rules); signUp=true (SignUpFlag) is what ExplicitSignUp requires before a user is created same
GET /oauth/<provider>/callback operation oauth.CallbackEndpoint(provider) (oauth.<provider>-callback); (*Plugin).Callback(ctx, provider, CallbackRequest) from Go, with ctx carrying the request whose flow cookie is checked; a provider not in use is ErrProviderUnknown for both Public, plus the flow cookie set by start; iss must match the provider's AuthorizationIssuer when it has one; user is handed to a PostedProfile provider. For a provider named in AllowProviderInitiated or RestartProviderInitiated, a request with a code and no state is a provider-initiated sign-in instead (see Options) none; 30 per IP per minute for a provider named in either
POST /oauth/<provider>/callback (form body code, state, user, error) operation oauth.FormPostEndpoint(provider) (oauth.<provider>-form-post); only for a FormPoster Public; reads no cookie, writes nothing, and answers a redirect to the GET callback with the same fields (a user over 1024 characters is dropped), so the flow cookie reaches the real callback none
POST /oauth/<provider>/id-token {"idToken","nonce","signUp","accessToken"} operation oauth.IDTokenEndpoint(provider) (oauth.<provider>-id-token); only for an IDTokenVerifier Public; a signed-in caller links instead of signing in; an accessToken is taken only when the ID token's at_hash binds it (else oauth.id_token_invalid), and is stored under StoreTokens; each token is accepted once (oauth.id_token_replayed after) 30 per IP per minute
POST /oauth/<provider>/logout {"returnTo"} (LogoutRequest; its provider may be omitted here, and another provider's name is ErrLogoutProvider) operation oauth.LogoutEndpoint(provider) (oauth.<provider>-logout); only for a Logouter SignedIn; returnTo is optional, passes the same TrustsReturnURL rule as a sign-in's returnTo (a path is made absolute against the base URL), and is sent as post_logout_redirect_uri instead of PostLogoutURL; an untrusted one is ErrBadReturnTo and the session is not ended none
POST /oauth/logout {"provider":"okta","returnTo":"/bye"} operation oauth.EndpointLogout (oauth.logout); exists when any provider is a Logouter SignedIn; the per-provider route's code path, returnTo check included, for the provider named in the body. No provider is ErrLogoutProvider (nothing is guessed from the linked accounts); one that is not configured or has no logout is ErrLogoutUnsupported; the session survives every refusal. On a provider's own route provider may be omitted, and naming another is ErrLogoutProvider none
sign-in buttons (*Plugin).SignInMethods() (authhttp.UIMethod), read by authui's sign-in and sign-up pages One authhttp.SignInMethod per provider in use, in configuration order: ID oauth.<provider>, Kind oauth, label "Continue with ", Route the provider's GET start route; none for a provider skipped or whose start is switched off, none before auth.New none
GET /oauth/providers operation oauth.EndpointProviders; (*Plugin).Providers() from Go Public; {"providers":[{"id":"google","name":"Google"}]}, in configuration order (ProviderInfo), ids and display names only; a provider SkipBrokenProviders left out is not listed none
POST /oauth/unlink {"provider":"github","accountId":"acc_…"} (*Plugin).Unlink(ctx, provider); (*Plugin).UnlinkAccount(ctx, provider, accountID) for one of several accounts of a provider (accountId from /oauth/accounts; an id that is not the caller's is ErrNotLinked). Without an id the oldest account of the provider goes FreshSignIn none
GET /oauth/accounts operation oauth.EndpointAccounts; (*Plugin).Accounts(ctx, userID) for any user; each account carries scopes, the scopes the provider said it granted (with StoreTokens; [] otherwise), never a token SignedIn none
POST /oauth/reauthenticate {"provider":"google","returnTo":"/settings"} operation oauth.EndpointReauthenticate (oauth.reauthenticate); (*Plugin).Reauthenticate(ctx, in). Re-authentication with a linked provider: answers {"url"} (no redirect) and binds the flow to the current session; the provider's callback then makes that session fresh (auth.Reauthenticate, the second factor asked as at OAuth sign-in) and lands on returnTo with ?reauth=fresh or second_factor plus reauthTicket, never issuing a session. Any provider account not linked to the session's user is ErrReauthNotLinked, on errorTo (default returnTo) with ?error= SignedIn, origin-checked; refused for a pending session, an API key and an impersonation 30 per IP per minute, 10 per user per 15 minutes
POST /oauth/reauthenticate-id-token {"provider":"apple","idToken":"…","nonce":"…"} operation oauth.EndpointReauthenticateIDToken (oauth.reauthenticate-id-token), present when a provider verifies ID tokens; (*Plugin).ReauthenticateIDToken(ctx, in). Re-authentication for a native app that cannot follow a redirect: the ID token is verified as at native sign-in (verifyNative: key set, issuer, audience, lifetime, nonce rule, at_hash for an access token) and must name an account linked to the signed-in user (ErrReauthNotLinked otherwise; nothing linked or created). Answers auth.Reauthentication (fresh, or the second factor's ticket), never issuing a session. Each token is accepted once, shared with native sign-in (WithIDTokenReplayGuard), so a used token is oauth.id_token_replayed SignedIn; refused for a pending session, an API key and an impersonation before the token is verified 30 per IP per minute, 10 per user per 15 minutes
POST /oauth/access-token {"provider":"google"} operation oauth.EndpointAccessToken (oauth.access_token); only with ExposeAccessTokens. Answers {"accessToken","accessTokenExpiresAt","scopes","idToken"}, refreshed when due; a provider not linked or not configured is ErrNoTokens SignedIn, origin-checked; only the caller's own account 30 per IP per minute
Go only (*Plugin).Tokens(ctx, userID, provider) none (app code) none
Go only (*Plugin).ImportAccount(ctx, ImportAccount{UserID, Provider, ProviderAccountID, Email}): links an account from another system to an existing user without a sign-in, for an import; ErrProviderUnknown for a provider not configured, ErrAccountLinkedElsewhere when the provider account is already linked none (app code) none
Go only (*Plugin).Refresh(ctx, userID, provider): renews the stored tokens now, whatever their expiry (ErrCannotRefresh without a refresh token or a Refresher) none (app code) none
Go only (*Plugin).Profile(ctx, userID, provider): the provider's current profile read with the stored tokens, for a ProfileFetcher (ErrProfileUnsupported otherwise); nothing is written to the user none (app code) none

Start answers 302 to the provider and sets the flow cookie. Callback answers 302 to returnTo (default /) and, unless it was a link flow, issues a session. The id-token route answers the same CallbackResult as JSON with the session issued (a cookie, or Set-Auth-Token in bearer mode) and no redirect: it is for an app, not a browser following links; no provider tokens are stored on that path. The ID token is checked for signature (RS256, ES256 or EdDSA against the provider's key set, refetched for an unknown kid at most once a minute and at least once a day), iss, aud, exp and iat (with 30 seconds of leeway), and nonce: the claim must equal the request's nonce or its SHA-256 hex (Apple's native flow hashes it); a token with a nonce needs the request to carry one, and a request with a nonce needs the token to carry it. Logout ends the session here through the core's own sign-out, then answers 302 to the provider's end-session endpoint with id_token_hint (when StoreTokens kept one), client_id and post_logout_redirect_uri (the request's returnTo, else PostLogoutURL); a Go caller gets the URL in LogoutResult. Accounts are listed oldest first, and accounts linked in the same instant in id order, so every engine returns the same order. CallbackResult also reports Created, Linked and SecondFactorRequired. Tokens refreshes an access token that expires within RefreshMargin (1 minute) when the account has a refresh token and the provider is a Refresher. An API key is refused by unlink and accounts (auth.ErrAPIKeyRefused).

Tables and columns

The plugin owns auth_account (TableNameAccount, alias acc), created by migration 0001_account (owner oauth):

Column Constant Meaning
id ColAccountID Primary key, acc_...
user_id ColAccountUserID Owner; deleted with the user by a.DeleteUser (declared in UserTables; no foreign key)
provider ColAccountProvider Provider name, e.g. github
subject ColAccountSubject The provider's stable id for the person, never the email
email ColAccountEmail Address the provider reported, default ''
created_at ColAccountCreated When linked
access_token_sealed ColAccountAccess Sealed access token; '' unless StoreTokens
refresh_token_sealed ColAccountRefresh Sealed refresh token; '' unless StoreTokens
token_expires_at ColAccountExpires Access token expiry, NULL when unknown
token_scope ColAccountScope The scope the provider said it granted at the last exchange or refresh, '' when it did not say (migration 0003_account_token_scope)
refresh_token_expires_at ColAccountRefreshExpires When the refresh token expires, for providers that say (refresh_token_expires_in, refresh_expires_in); NULL when unknown (migration 0003)
id_token_sealed ColAccountIDToken Sealed ID token for id_token_hint; NULL unless StoreTokens and the provider returned one. Added by migration 0002_account_id_token

Constraints: UNIQUE (provider, subject), one provider account belongs to one user. Index auth_account_user_idx on user_id. Typed columns for queries are exported as AccountID, AccountUserID, and so on. These columns are not in the core's stable-column contract (stability_test.go covers auth_user, auth_identity and auth_session only), so treat them as readable but not frozen across minor versions.

Errors

Variable Code HTTP When
ErrStateInvalid oauth.state_invalid 400 Missing, foreign, spent or expired state; state from another provider; link flow finished by a different or signed-out user
ErrProviderDenied oauth.denied 400 The provider returned error (the user cancelled)
ErrProviderFailed oauth.provider_failed 502 Discovery or the code exchange failed; details are logged, never sent
ErrAccountExists oauth.account_exists 409 The provider address matches an identity but the provider did not verify it
ErrAccountLinkedElsewhere oauth.linked_elsewhere 409 The provider account belongs to another user
ErrNotLinked oauth.not_linked 404 Unlink of a provider the user has not linked
ErrReauthNotLinked oauth.reauth_not_linked 403 Re-authentication with a provider the user has no account at, or whose callback or ID token brought back a provider account not linked to the signed-in user (another user's, or one never linked)
ErrBadReturnTo oauth.bad_return_to 400 returnTo or errorTo is neither a path on this site, an absolute URL on a trusted origin, nor a deep link in a scheme auth.WithTrustedOrigins lists ("myapp://"); the rule is the core's TrustsReturnURL
ErrRefreshFailed oauth.refresh_failed 502 Tokens could not refresh an expiring token
ErrNoTokens oauth.no_tokens 404 Tokens without StoreTokens, without a linked account, or for an account linked before tokens were stored
ErrExchange none none Wrapped in every provider-call failure; logged, the client sees ErrProviderFailed
ErrHostedDomain none none GoogleProfileFor: the account's hd is not the required domain; wraps ErrExchange
ErrProviderIncomplete none none Configuration, returned by auth.New: an *OAuth2 lacking AuthURL, TokenURL, ClientID or FetchProfile, an unknown TokenAuth, or a PublicClient with a secret
ErrSignUpDisabled oauth.sign_up_disabled 403 NoSignUp is set and the callback would have created a user
ErrEmailUnverified oauth.email_unverified 403 RequireVerifiedEmail is set and the profile's email is missing or unverified (not in a link flow)
ErrBadScope oauth.bad_scope 400 StartRequest.Scopes names a scope outside the provider's OptionalScopes
ErrBadParam oauth.bad_param 400 StartRequest.Params does not parse, is too long, or names a parameter outside the provider's OptionalParams
ErrEmailNotFound oauth.email_not_found 403 RequireEmail or VerifyEmailBeforeSignIn is set and the profile carries no email (not in a link flow)
ErrEmailNotVerified oauth.email_not_verified 403 Never returned: the code a sign-in held by VerifyEmailBeforeSignIn lands with (?error=), beside emailVerificationRequired: true
ErrRequestParams oauth.params_unsupported 400 prompt, loginHint or scopes sent to a Provider that is not a ParamsProvider
ErrEmailMismatch oauth.email_mismatch 409 RequireSameEmailOnLink is set and the provider address is missing, unparsable, or not an identity of the signed-in user
ErrIDTokenReplayed oauth.id_token_replayed 401 The ID token was already accepted once, by a native sign-in or an ID-token re-authentication; the replay guard refused it and reported token.replay to the security stream
ErrIDTokenInvalid oauth.id_token_invalid 401 The ID token is malformed, uses an unlisted algorithm, names an unknown key, fails its signature, is expired or not yet valid, names another issuer or audience, or its nonce does not match; one answer for every reason, the reason is logged
ErrIDTokenUnsupported oauth.id_token_unsupported 400 The provider has no IDTokenConfig (an issuer whose discovery document has no jwks_uri)
ErrNonceRequired oauth.nonce_required 401 IDToken.RequireNonce is set and the token carries no nonce
ErrLogoutUnsupported oauth.logout_unsupported 404 Logout at a provider with no end-session endpoint; on the general route, a provider that is not configured or has no logout
ErrLogoutProvider oauth.logout_provider 400 The general logout route without a provider, or a provider's own route with another provider in the body
ErrDataTooLong oauth.data_too_long 400 StartRequest.Data is longer than 1024 characters
ErrSignUpNotRequested oauth.sign_up_not_requested 403 ExplicitSignUp applies and the flow would create a user without signUp=true
ErrProfileRefused oauth.profile_refused 403 A ValidateProfile hook refused with an error that is not an *auth.Error; the reason is logged
ErrCannotRefresh oauth.cannot_refresh 404 Refresh for an account with no refresh token, or at a provider that is not a Refresher
ErrProfileUnsupported oauth.profile_unsupported 404 Profile at a provider that is not a ProfileFetcher, or whose profile exists only in the exchange's ID token
ErrProviderUnknown, ErrImportSubject none none ImportAccount for a provider the plugin was not built with, or without a user id or provider account id
ErrAssertionConfig, ErrAssertionKey none none Configuration: PrivateKeyJWT without ClientAssertion or the reverse (returned by auth.New); a key for ClientAssertion that is neither ECDSA P-256 nor RSA
ErrJWKSFailed none none The provider's key set could not be read; the client sees ErrProviderFailed
ErrFallbackIncomplete, ErrProviderInitiatedConfig, ErrAllProvidersBroken, ErrIDTokenReplayConfig none none Configuration, returned by auth.New: WithIDTokenReplayGuard beside AllowIDTokenReplay, or the default replay guard over a verification store that cannot refuse a duplicate; an incomplete OIDC Fallback; AllowProviderInitiated on a provider that cannot verify ID tokens, or either provider-initiated mode on an unknown provider or both on one; every provider left out under SkipBrokenProviders
ErrIDTokenConfig, ErrAppleKey, ErrAppleSecret none none Configuration: a bad IDTokenConfig (returned by auth.New); a .p8 file that is not a P-256 PKCS #8 key; AppleClientSecret with an empty team id, client id, key id or a nil key
ErrPublicClientPKCE, ErrCallbackParam, ErrExposeNeedsStoreTokens, ErrPhotoSize none none Configuration: NoPKCE with PublicClient, or a CallbackParams entry outside CallbackParamValues (both returned by auth.New); ExposeAccessTokens without StoreTokens (returned by auth.New); MicrosoftPhoto with a size Graph does not serve
ErrServerContextTooLong none 500 A WithServerContext function returned more than 1024 characters as JSON; the start fails

Unlinking the last way into an account answers the core's auth.last_sign_in_method (409).

Security notes

Property Pinned by
PKCE S256 on every flow unless the provider sets NoPKCE (never with PublicClient); the verifier is sent at the exchange and differs from the challenge TestPKCEChallengeIsS256, TestOAuth_SignInCreatesUserThenLinksByVerifiedEmail, TestNoPKCE_LeavesTheChallengeAndVerifierOut, TestValidate_NoPKCEAndCallbackParams
The client secret never appears in the browser URL TestAuthCodeURL_CarriesStateAndChallenge
A callback is accepted only in the browser that started it (flow cookie), the login-CSRF defence TestOAuth_CallbackNeedsTheFlowCookie
State is single-use, bound to its provider, and expires TestTokensOAuth_CallbackRefusals
Automatic linking only when both the provider address and the existing identity are verified TestOAuth_UnverifiedProviderEmailDoesNotLink, TestOAuth_SignInCreatesUserThenLinksByVerifiedEmail
A provider account never moves to a second user, including under a concurrent callback TestTokensOAuth_ReturningLinkingAndUnlinking, TestTokensOAuth_LosingARaceIsLinkedElsewhere
returnTo accepts a same-site path, a trusted origin or a trusted deep-link scheme, and nothing else (no //host, no backslash) TestSafeReturnTo, the core's TrustsReturnURL tests
OIDC discovery refuses a document naming another issuer TestOIDC_DiscoversAndChecksTheIssuer
Stored tokens are sealed and bound to their account row; a changed key or tampered column fails to open (auth.ErrSealedCorrupt) TestOAuth_StoreTokensSealsAndReadsBack, TestTokensOAuth_Tokens
A Sealer (StoreTokensWith, auth.WithSealer) seals and opens in that order of precedence below a StoreTokens key, binds each token to its account, and its errors fail the write or the read, never yield an empty token TestStoreTokens_SealerPrecedence, TestStoreTokens_SealerErrorsFailClosed
Without a key, tokens seal under the app secret's derived key; a rotated secret keeps them opening, a dropped one does not, an explicit key wins TestStoreTokens_DerivesTheKeyFromTheAppSecret, TestTokensOAuth_StoreTokensUnderTheAppSecret
Unlink never removes the last way in TestOAuth_UnlinkRefusesTheLastWayIn
Re-authentication refreshes the session it was started on, with no new session or token, only with a provider account linked to that session's user; another user's account, an unlinked one, a replayed state, another session, an impersonation and a signed-out callback are refused, and the second factor is asked as at OAuth sign-in TestOAuthReauth_RefreshesTheSameSession, TestOAuthReauth_OnlyALinkedAccountOfThisUser, TestOAuthReauth_RefusedCallers, TestOAuthReauth_AsksTheSecondFactorAsSignInDoes
Each ID token is accepted once: a replayed one is oauth.id_token_replayed (401 over HTTP), issues nothing and reaches the security stream as token.replay; a token refused by verification is not spent; of concurrent posts of one token exactly one signs in; the claim survives a sweep until exp plus leeway; a key-value verification store refuses it too; WithIDTokenReplayGuard is asked with the key, provider and expiry and its refusal or failure stops the call; AllowIDTokenReplay lets a token in twice; both together, a nil guard and a store that keeps duplicates fail auth.New TestOAuthIDTokenReplay_SignInOnce, TestOAuthIDTokenReplay_ConcurrentSignIn, TestOAuthIDTokenReplay_ClaimHeldUntilExpiry, TestOAuthIDTokenReplay_SwapAndEscapeHatch, TestOAuthReauthIDToken_RealVerification, TestIDTokenKey, TestIDTokenUntil
ID-token re-authentication refreshes the bearer or cookie session it is posted on, with no new session or token, only with a verified token of an account linked to that user; another user's token, an unlinked account, another audience, issuer or key, an expired token, a nonce mismatch, an unbound access token, a pending session and an impersonation are refused, the second factor is asked with the oauth method, and refused proofs reach the security stream TestOAuthReauthIDToken_OnlyALinkedAccountOfThisUser, TestOAuthReauthIDToken_RealVerification, TestOAuthReauthIDToken_RefusedCallers, TestOAuthReauthIDToken_AsksTheSecondFactor, TestOAuthReauthIDToken_HTTPBearerAndCookie
Every database failure on each flow reaches the caller TestTokensOAuth_Faults, TestTokensOAuth_NativeFaults
An ID token verifies only under its own algorithm and a listed one (none and HMAC are refused), with its issuer, audience, lifetime and nonce checked; a tampered payload fails TestIDToken_VerifiesEveryAcceptedAlgorithm, TestIDToken_Rejections, TestIDToken_Nonce
An unknown kid refetches the key set at most once a minute, so forged tokens cannot flood the provider TestIDToken_KeySetRefreshIsBounded
The profile taken from an id_token at the exchange is bound to the flow by the PKCE challenge as nonce TestExchange_ProfileFromIDTokenUsesTheChallengeAsNonce
Apple's client secret verifies under the .p8 key and is renewed before it expires TestApple_KeyAndClientSecret
The id-token route creates, signs in or links under the callback's rules, refuses a wrong token or nonce, and is rate-limited per IP TestTokensOAuth_IDTokenSignIn, TestTokensOAuth_IDTokenRespectsSignUpAndEmailSwitches, TestTokensOAuth_IDTokenRateLimit
Logout ends the session here before sending the browser to the provider, and a provider that cannot be reached does not keep the session alive TestTokensOAuth_Logout
A logout's returnTo is sent only when trusted, a path becomes absolute against the base URL (refused when there is none), and an untrusted one leaves the session alive TestTokensOAuth_LogoutReturnTo, TestLogoutReturn_PathNeedsBaseURL
Every built-in provider shape passes the conformance kit: Google, GitHub, *OAuth2 with userinfo, with an ID-token profile, as a public client and with a GetToken hook, oauth.OIDC (also on its Fallback) and the Okta, Keycloak, GitLab and Zitadel presets, Discord and Zoom TestConformance_* in oauthtest
A ValidateProfile refusal writes nothing, and a failing OnResolved rolls the new user back; both hooks run on the id-token route too TestTokensOAuth_ProfileHooks
RequireEmail refuses an email-less profile before writing; VerifyEmailBeforeSignIn keeps the user, issues no session until the address is verified on the callback, id-token and provider-initiated routes, and signs in after verification TestOAuth_RequireEmail, TestOAuth_VerifyEmailBeforeSignIn (integration, three engines)
An id-token accessToken is stored only when at_hash binds it (the OpenID Connect Core example vector included) TestBindAccessToken, TestOAuth_IDTokenAccessToken
params forwards only allow-listed names, never a protocol parameter; provider calls refuse redirects on the default and an app client TestStartParams_AllowListed, TestProviderCalls_RefuseRedirects
AllowUnlinkingAll lets the last method go; the default refuses TestOAuth_AllowUnlinkingAll
Under ExplicitSignUp a stranger is refused without the flag, on the redirect and the id-token route, and NoSignUp still wins TestTokensOAuth_ExplicitSignUp
A failed callback without ErrorURL or errorTo lands on the core's auth.WithErrorURL page, and still answers JSON when none is set TestTokensOAuth_FailedCallbackFallsBackToTheCoreErrorURL
A callback whose iss is missing or another issuer's is refused when the provider announces one (RFC 9207) TestTokensOAuth_NewUserToAndIssuerCheck
The client assertion verifies under the registered key, names the token endpoint as audience, carries a fresh jti, and a TokenParams entry cannot replace it TestClientAssertion_ES256AndRS256, TestTokenAuth_PrivateKeyJWT
Unlink revokes the stored tokens at the provider and stands when the provider is down; the refresh token is preferred TestTokensOAuth_UnlinkRevokes, TestRevoke_RFC7009
A Google ID token from another Workspace domain is refused under HostedDomain TestGoogleIDTokens_HostedDomain
An imported account signs its user in, never a second user, and an already-linked provider account is refused TestTokensOAuth_ImportAccount
Every database failure on hooks, Refresh, Profile, ImportAccount and a revoking unlink reaches the caller TestTokensOAuth_Round3Faults
The general logout route names its provider (never guessed), shares the per-provider route's returnTo check, and every refusal leaves the session alive TestTokensOAuth_GeneralLogoutRoute, TestLogoutAny_RefusesWithoutGuessing
The discovery fallback is used only while the document is unreachable, never for a document naming another issuer or lacking an endpoint, and discovery is retried after the interval TestFallback_*, TestConformance_OIDCFallback
SkipBrokenProviders leaves out exactly the providers that fail their check, discovery or key set, from routes, lists and lookups; without it nothing is fetched at auth.New and a bad configuration still fails it TestSkipBroken_*
GetToken replaces the exchange without bypassing PKCE: it is handed the flow's verifier, its error comes back unchanged, and the conformance kit passes through it TestGetToken_*, TestConformance_OAuth2GetToken, TestTokensOAuth_ProvidersFallbackSkipAndGetTokenOverHTTP
A provider-initiated sign-in happens only for a provider named in AllowProviderInitiated (a capable provider that was not named, and every other provider, still refuse a state-less callback), verifies the ID token with no nonce allowed and the profile's subject bound to it, never links by address, and replaces the browser's session only once the person is known TestTokensOAuth_ProviderInitiatedSignIn, TestExchangeInitiated_*, TestVerifyInitiated_NonceRules, TestAllowProviderInitiated_Validation
RestartProviderInitiated never exchanges the tile's code: it answers a fresh flow bound to the browser, whose callback is checked as usual TestTokensOAuth_RestartProviderInitiated, TestRestartProviderInitiated_Validation
Server context is set by the server only, crosses the redirect intact, reaches the hooks and the callback's Go result, and never the callback's JSON TestTokensOAuth_ServerContextCrossesTheRedirect, TestTokensOAuth_ServerContextFailures
The access-token route exists only with ExposeAccessTokens and StoreTokens, needs a session, answers only the caller's own token, is rate-limited per IP, and never sends the refresh token; the accounts list shows granted scopes and no token TestTokensOAuth_ExposeAccessTokens, TestTokensOAuth_AccessTokenRouteIsRateLimited, TestTokensOAuth_AccountsListGrantedScopes, TestTokensOAuth_Round6Faults
The callback's device_id and state reach a provider's exchange (VK ID) on the plugin and on authgate TestTokensOAuth_CallbackValuesReachTheExchange, TestGate_CallbackValuesReachTheExchange
A wired plugin offers one GET button per provider in configuration order, labelled by display name and pointing at the start route; a provider whose start is switched off gets none; an unwired plugin offers nothing TestSignInMethods_OneButtonPerProvider

Limits, honestly: on the redirect flow the profile comes from the userinfo endpoint with the access token (OpenID Connect makes it authoritative), so the id_token is checked only when IDToken.ProfileFromToken is set. The key-set fetch ignores the provider's cache headers and uses its own bounds. The id-token route stores no provider tokens. RFC 9207 iss on the callback is checked when the provider announces it (AuthorizationIssuer, see the options table). Provider responses are read up to maxProviderBody (1 MiB). Two callers refreshing at once with a provider that rotates refresh tokens can make the slower one get ErrRefreshFailed; it should call again. Start is rate-limited per process unless the app passes auth.WithRateStore.

Example