Documentation
¶
Overview ¶
Package authgen is a backend-only authentication library for Go, inspired by Auth.js. It provides email/password, passkeys (WebAuthn), magic links, email/SMS one-time codes, OAuth 2.0/OIDC, SAML SSO, API keys and anonymous sessions, with MFA (TOTP, WebAuthn, email/SMS codes, recovery codes) on top of opaque, revocable database sessions.
The application owns the database: authgen runs only DML against the PostgreSQL pool it is given and never creates or alters tables. See the schema package and cmd/authgen to generate the DDL.
Example ¶
A typical production setup: your pool, your tables, REST mounted at /auth.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/mjahidhasand10/authgen"
"github.com/mjahidhasand10/authgen/notify"
"github.com/mjahidhasand10/authgen/providers/oauth"
"github.com/mjahidhasand10/authgen/transport/rest"
)
type noopEmail struct{}
func (noopEmail) SendEmail(context.Context, notify.Email) error { return nil }
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
a, err := authgen.New(authgen.Config{
Pool: pool,
BaseURL: "https://api.example.com/auth",
Secrets: []string{os.Getenv("AUTHGEN_SECRET")},
TrustedOrigins: []string{"https://app.example.com"},
Methods: authgen.Methods{Password: true, MagicLink: true, Passkey: true},
WebAuthn: authgen.WebAuthnConfig{RPID: "example.com"},
OAuth: authgen.OAuthConfig{Providers: []*oauth.Provider{oauth.Google("id", "secret")}},
Email: noopEmail{}, // your provider
MFA: authgen.MFAConfig{Require: true},
})
if err != nil {
log.Fatal(err)
}
if err := a.CheckSchema(ctx); err != nil { // read-only
log.Fatal(err)
}
mux := http.NewServeMux()
rest.Mount(mux, "/auth", a)
mux.Handle("GET /api/me", a.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, authgen.UserFromContext(r.Context()).ID)
})))
log.Fatal(http.ListenAndServe(":8080", mux))
}
Output:
Example (SchemaMapping) ¶
Map authgen onto an existing users table and generate the remaining DDL for your migration tool.
package main
import (
"fmt"
"github.com/mjahidhasand10/authgen/schema"
)
func main() {
m := schema.Mapping{
Tables: map[string]string{"users": "users"},
Columns: map[string]map[string]string{"users": {"email": "email_address"}},
}
r := m.MustResolve()
fmt.Println(r.Table("users"), r.Col("users", "email"), r.Table("sessions"))
}
Output: "users" "email_address" "authgen_sessions"
Index ¶
- Constants
- Variables
- func AnonymousUserID(u *store.User) string
- func HasAMR(s *store.Session, method string) bool
- func HasScope(k *store.APIKey, scope string) bool
- func NormalizeEmail(s string) (string, bool)
- func NormalizePhone(s string) (string, bool)
- func UserFromContext(ctx context.Context) *store.User
- func ValidCodeChallenge(c string) bool
- func WithActor(ctx context.Context, userID string) context.Context
- func WithPrincipal(ctx context.Context, p *Principal) context.Context
- func WithRequestMeta(ctx context.Context, m RequestMeta) context.Context
- func WithSessionOptions(ctx context.Context, o SessionOptions) context.Context
- func WriteError(w http.ResponseWriter, err error)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type APIKeyConfig
- type APIKeyInput
- type APIKeyView
- type AccountView
- type AlertsConfig
- type AnonymousConfig
- type AuditConfig
- type Auth
- func (a *Auth) AccountTokens(ctx context.Context, userID, provider string) (*oauth2.Token, error)
- func (a *Auth) AdminDeleteUser(ctx context.Context, actorID, userID string) error
- func (a *Auth) AdminResetMFA(ctx context.Context, actorID, userID string, includePasskeys bool) error
- func (a *Auth) AdminRevokeSessions(ctx context.Context, actorID, userID string) (int64, error)
- func (a *Auth) AdminSetDisabled(ctx context.Context, actorID, userID string, disabled bool) error
- func (a *Auth) Authenticate(r *http.Request) (*Principal, error)
- func (a *Auth) AuthenticateAPIKey(ctx context.Context, key string) (*store.APIKey, *store.User, error)
- func (a *Auth) BeginBiometricEnrollment(ctx context.Context, s *store.Session, u *store.User) (*BiometricChallenge, error)
- func (a *Auth) BeginBiometricSignIn(ctx context.Context) (*BiometricChallenge, error)
- func (a *Auth) BeginOAuth(ctx context.Context, providerID string, opts OAuthStartOptions) (*OAuthStart, error)
- func (a *Auth) BeginPasskeyLogin(ctx context.Context) (options *protocol.CredentialAssertion, ceremonyID string, err error)
- func (a *Auth) BeginPasskeyLoginWithOptions(ctx context.Context, o PasskeyLoginOptions) (options *protocol.CredentialAssertion, ceremonyID string, err error)
- func (a *Auth) BeginPasskeyRegistration(ctx context.Context, s *store.Session, u *store.User) (*protocol.CredentialCreation, error)
- func (a *Auth) BeginSAML(ctx context.Context, opts SAMLStartOptions) (*SAMLStart, error)
- func (a *Auth) BeginTOTPEnrollment(ctx context.Context, s *store.Session, u *store.User) (*TOTPEnrollment, error)
- func (a *Auth) BeginWebAuthnMFA(ctx context.Context, challengeToken string) (*protocol.CredentialAssertion, error)
- func (a *Auth) BeginWebAuthnReauth(ctx context.Context, s *store.Session, u *store.User) (*protocol.CredentialAssertion, error)
- func (a *Auth) ChangePassword(ctx context.Context, s *store.Session, u *store.User, ...) error
- func (a *Auth) CheckCSRF(r *http.Request) error
- func (a *Auth) CheckSchema(ctx context.Context) error
- func (a *Auth) Cleanup(ctx context.Context) (CleanupResult, error)
- func (a *Auth) ClearMFACookie(w http.ResponseWriter)
- func (a *Auth) ClearOAuthCookie(w http.ResponseWriter)
- func (a *Auth) ClearSAMLCookie(w http.ResponseWriter)
- func (a *Auth) ClearSessionCookie(w http.ResponseWriter)
- func (a *Auth) Config() Config
- func (a *Auth) ConfirmEmailChange(ctx context.Context, token string) (*store.User, error)
- func (a *Auth) ConfirmPhone(ctx context.Context, u *store.User, phone, code string) (*store.User, error)
- func (a *Auth) ConfirmTOTPEnrollment(ctx context.Context, s *store.Session, u *store.User, code string) (recoveryCodes []string, err error)
- func (a *Auth) ContextWithRequest(r *http.Request) context.Context
- func (a *Auth) CreateAPIKey(ctx context.Context, s *store.Session, u *store.User, in APIKeyInput) (*CreatedAPIKey, error)
- func (a *Auth) CreateExchangeCode(ctx context.Context, res *AuthResult, codeChallenge string) (string, error)
- func (a *Auth) CreateSAMLConnection(ctx context.Context, in SAMLConnectionInput) (*store.SAMLConnection, error)
- func (a *Auth) DeletePasskey(ctx context.Context, s *store.Session, u *store.User, id string) error
- func (a *Auth) DeleteSAMLConnection(ctx context.Context, id string) error
- func (a *Auth) DeleteUser(ctx context.Context, userID string) error
- func (a *Auth) DisableMFAChannel(ctx context.Context, s *store.Session, u *store.User, channel string) error
- func (a *Auth) DisableTOTP(ctx context.Context, s *store.Session, u *store.User) error
- func (a *Auth) DisableUser(ctx context.Context, userID string) error
- func (a *Auth) EnableMFAChannel(ctx context.Context, s *store.Session, u *store.User, channel string) ([]string, error)
- func (a *Auth) EnableUser(ctx context.Context, userID string) error
- func (a *Auth) ExchangeCode(ctx context.Context, code, verifier string) (*AuthResult, error)
- func (a *Auth) FinishBiometricEnrollment(ctx context.Context, s *store.Session, u *store.User, assertion string) error
- func (a *Auth) FinishPasskeyLogin(ctx context.Context, ceremonyID string, response []byte) (*AuthResult, error)
- func (a *Auth) FinishPasskeyRegistration(ctx context.Context, s *store.Session, u *store.User, name string, ...) (*PasskeyRegistration, error)
- func (a *Auth) GetUser(ctx context.Context, id string) (*store.User, error)
- func (a *Auth) GetUserDetails(ctx context.Context, userID string) (*UserDetails, error)
- func (a *Auth) HandleOAuthCallback(ctx context.Context, providerID string, r *http.Request) (*OAuthOutcome, error)
- func (a *Auth) HandleSAMLACS(ctx context.Context, connectionID string, r *http.Request) (*SAMLOutcome, error)
- func (a *Auth) HandleSAMLLogoutResponse(ctx context.Context, connectionID string, r *http.Request) error
- func (a *Auth) IsNativeRedirect(raw string) bool
- func (a *Auth) IsSafeRedirect(raw string) bool
- func (a *Auth) IsTrustedOrigin(origin string) bool
- func (a *Auth) LinkBiometricSubject(ctx context.Context, userID, subject string) error
- func (a *Auth) ListAPIKeys(ctx context.Context, userID string) ([]APIKeyView, error)
- func (a *Auth) ListAccounts(ctx context.Context, userID string) ([]AccountView, error)
- func (a *Auth) ListAuditEvents(ctx context.Context, q store.AuditQuery) ([]*store.AuditEvent, error)
- func (a *Auth) ListPasskeys(ctx context.Context, userID string) ([]PasskeyView, error)
- func (a *Auth) ListSAMLConnections(ctx context.Context) ([]*store.SAMLConnection, error)
- func (a *Auth) ListSessions(ctx context.Context, userID string) ([]*store.Session, error)
- func (a *Auth) ListUsers(ctx context.Context, q store.UserQuery) ([]*store.User, error)
- func (a *Auth) MFAChallengeFromRequest(r *http.Request) string
- func (a *Auth) MFAEnrollmentRequired(ctx context.Context, u *store.User) (bool, error)
- func (a *Auth) MFAMethods(ctx context.Context, u *store.User) ([]string, error)
- func (a *Auth) MetaFromRequest(r *http.Request) RequestMeta
- func (a *Auth) Middleware(next http.Handler) http.Handler
- func (a *Auth) NewCSRFToken(w http.ResponseWriter) string
- func (a *Auth) PrepareRequest(w http.ResponseWriter, r *http.Request) context.Context
- func (a *Auth) Providers() []*oauth.Provider
- func (a *Auth) Reauthenticate(ctx context.Context, s *store.Session, u *store.User, in ReauthInput) (string, error)
- func (a *Auth) RecoveryCodesRemaining(ctx context.Context, userID string) (int, error)
- func (a *Auth) RegenerateRecoveryCodes(ctx context.Context, s *store.Session, u *store.User) ([]string, error)
- func (a *Auth) RenamePasskey(ctx context.Context, userID, id, name string) error
- func (a *Auth) RequestEmailChange(ctx context.Context, s *store.Session, u *store.User, newEmail string) error
- func (a *Auth) RequestEmailOTP(ctx context.Context, email string) error
- func (a *Auth) RequestMagicLink(ctx context.Context, email, callbackURL string) error
- func (a *Auth) RequestMagicLinkWithOptions(ctx context.Context, o MagicLinkOptions) error
- func (a *Auth) RequestPasswordReset(ctx context.Context, email string) error
- func (a *Auth) RequestPhoneVerification(ctx context.Context, s *store.Session, u *store.User, phone string) error
- func (a *Auth) RequestSMSOTP(ctx context.Context, phone string) error
- func (a *Auth) RequireAPIKey(scopes ...string) func(http.Handler) http.Handler
- func (a *Auth) RequireFresh(ctx context.Context, s *store.Session, u *store.User) error
- func (a *Auth) RequireFreshSession(next http.Handler) http.Handler
- func (a *Auth) RequireMFA(next http.Handler) http.Handler
- func (a *Auth) RequireSession(next http.Handler) http.Handler
- func (a *Auth) RequireUser(next http.Handler) http.Handler
- func (a *Auth) ResetPassword(ctx context.Context, token, newPassword string) error
- func (a *Auth) ResolveRedirect(raw, fallback string) string
- func (a *Auth) RevokeAPIKey(ctx context.Context, userID, id string) error
- func (a *Auth) RevokeOtherSessions(ctx context.Context, userID, keepID string) (int64, error)
- func (a *Auth) RevokeSession(ctx context.Context, userID, sessionID string) error
- func (a *Auth) SAMLLogoutURL(ctx context.Context, s *store.Session, u *store.User) (string, error)
- func (a *Auth) SAMLMetadata(ctx context.Context, connectionID string) ([]byte, error)
- func (a *Auth) SendMFACode(ctx context.Context, challengeToken, method string) error
- func (a *Auth) SendReauthCode(ctx context.Context, s *store.Session, u *store.User, channel string) error
- func (a *Auth) SendVerificationEmail(ctx context.Context, email string) error
- func (a *Auth) SessionCookieName() string
- func (a *Auth) SessionFromRequest(r *http.Request) (*store.Session, *store.User, error)
- func (a *Auth) SessionPayload(ctx context.Context, s *store.Session, u *store.User) (map[string]any, error)
- func (a *Auth) SetMFACookie(w http.ResponseWriter, p *MFAPending)
- func (a *Auth) SetSessionCookie(w http.ResponseWriter, is *IssuedSession)
- func (a *Auth) SetSessionToken(w http.ResponseWriter, token string, s *store.Session)
- func (a *Auth) Shutdown(ctx context.Context) error
- func (a *Auth) SignInAnonymously(ctx context.Context) (*IssuedSession, error)
- func (a *Auth) SignInWithBiometric(ctx context.Context, assertion string) (*AuthResult, error)
- func (a *Auth) SignInWithPassword(ctx context.Context, email, password string) (*AuthResult, error)
- func (a *Auth) SignOut(ctx context.Context, token string) error
- func (a *Auth) SignUp(ctx context.Context, in SignUpInput) (*SignUpResult, error)
- func (a *Auth) Store() store.Store
- func (a *Auth) TakeSAMLPostForm(ctx context.Context, token string) (*SAMLPostForm, error)
- func (a *Auth) TokenFromRequest(r *http.Request) (token string, fromCookie bool)
- func (a *Auth) UnlinkAccount(ctx context.Context, s *store.Session, u *store.User, accountID string) error
- func (a *Auth) UpdateProfile(ctx context.Context, userID string, p ProfileUpdate) (*store.User, error)
- func (a *Auth) UpdateSAMLConnection(ctx context.Context, id string, in SAMLConnectionInput) (*store.SAMLConnection, error)
- func (a *Auth) ValidateSession(ctx context.Context, token string) (*store.Session, *store.User, error)
- func (a *Auth) VerifyEmail(ctx context.Context, token, password string) (*store.User, error)
- func (a *Auth) VerifyEmailOTP(ctx context.Context, email, code, anonymousUserID string) (*AuthResult, error)
- func (a *Auth) VerifyMFA(ctx context.Context, in MFAVerifyInput) (*IssuedSession, error)
- func (a *Auth) VerifyMagicLink(ctx context.Context, token, anonymousUserID string) (*MagicLinkOutcome, error)
- func (a *Auth) VerifySMSOTP(ctx context.Context, phone, code, anonymousUserID string) (*AuthResult, error)
- type AuthResult
- type BiometricChallenge
- type BiometricConfig
- type BotProtectionConfig
- type CSRFConfig
- type Callbacks
- type CleanupResult
- type Config
- type CreatedAPIKey
- type Error
- type ErrorBody
- type Event
- type EventType
- type HIBPChecker
- type IssuedSession
- type MFAConfig
- type MFAPending
- type MFAVerifyInput
- type MagicLinkOptions
- type MagicLinkOutcome
- type Methods
- type OAuthConfig
- type OAuthOutcome
- type OAuthStart
- type OAuthStartOptions
- type PasskeyLoginOptions
- type PasskeyRegistration
- type PasskeyView
- type PasswordChecker
- type PasswordCheckerFunc
- type PasswordConfig
- type Principal
- type ProfileUpdate
- type RateLimitConfig
- type ReauthInput
- type RequestMeta
- type SAMLConfig
- type SAMLConnectionInput
- type SAMLOutcome
- type SAMLPostForm
- type SAMLStart
- type SAMLStartOptions
- type SMSPolicyConfig
- type SessionConfig
- type SessionOptions
- type SessionView
- type SignInAttempt
- type SignUpInput
- type SignUpResult
- type TOTPEnrollment
- type Templates
- type TokenConfig
- type URLs
- type UserDetails
- type UserView
- type WebAuthnConfig
Examples ¶
Constants ¶
const ( MFATOTP = "totp" MFAWebAuthn = "webauthn" MFARecovery = "recovery_code" MFAEmail = "email" MFASMS = "sms" )
MFA method identifiers.
const ( CaptchaHeader = "X-Captcha-Token" DeviceIDHeader = "X-Device-Id" )
Header names read by MetaFromRequest.
const ( AMRPassword = "pwd" AMRMagicLink = "magic_link" AMREmailOTP = "email_otp" AMRSMSOTP = "sms_otp" AMRPasskey = "passkey" // AMRUserVerified marks that a WebAuthn authenticator verified the user // on the device (fingerprint, face, iris or device PIN; WebAuthn does not // reveal which). AMRUserVerified = "uv" AMRAnonymous = "anonymous" AMRTOTP = "totp" AMRWebAuthn = "webauthn" AMRRecovery = "recovery_code" AMRMFAEmail = "mfa_email" AMRMFASMS = "mfa_sms" )
Authentication method references recorded on sessions (AMR).
const CSRFHeader = "X-CSRF-Token"
CSRFHeader is the request header carrying the double-submit CSRF token.
const EmailFactorLockout = 24 * time.Hour
EmailFactorLockout is how long email codes cannot serve as a second factor after a password reset (which already proved only the inbox).
const ExchangeTTL = 2 * time.Minute
ExchangeTTL is the lifetime of an exchange code.
Variables ¶
var ( ErrInvalidRequest = newErr("invalid_request", http.StatusBadRequest, "The request is invalid.") ErrInvalidCredentials = newErr("invalid_credentials", http.StatusUnauthorized, "Invalid credentials.") ErrForbidden = newErr("forbidden", http.StatusForbidden, "Not allowed.") ErrAccessDenied = newErr("access_denied", http.StatusForbidden, "Sign-in was denied.") ErrInvalidToken = newErr("invalid_token", http.StatusBadRequest, "The token or code is invalid or has expired.") ErrRateLimited = newErr("rate_limited", http.StatusTooManyRequests, "Too many attempts. Try again later.") ErrConflict = newErr("conflict", http.StatusConflict, "The resource already exists.") ErrNotFound = newErr("not_found", http.StatusNotFound, "Not found.") ErrEmailNotVerified = newErr("email_not_verified", http.StatusForbidden, "Email address is not verified.") ErrMethodDisabled = newErr("method_disabled", http.StatusNotFound, "This sign-in method is not enabled.") ErrReauthRequired = newErr("reauthentication_required", http.StatusForbidden, "Please confirm your identity again.") ErrMFARequired = newErr("mfa_required", http.StatusForbidden, "A second factor is required.") ErrMFAEnrollment = newErr("mfa_enrollment_required", http.StatusForbidden, "Set up two-step verification to continue.") ErrPasswordRequired = newErr("password_required", http.StatusForbidden, "Enter your password to confirm this email address, or open the link on the device you signed up from.") ErrCaptcha = newErr("captcha_required", http.StatusForbidden, "Please complete the bot check and try again.") ErrAccountNotLinked = newErr("account_not_linked", http.StatusConflict, "This email is already used by another sign-in method. Sign in with that method and link this account from your settings.") ErrWeakPassword = newErr("weak_password", http.StatusBadRequest, "The password does not meet the requirements.") ErrBreachedPassword = newErr("breached_password", http.StatusBadRequest, "This password has appeared in a data breach. Choose a different password.") ErrCSRF = newErr("csrf", http.StatusForbidden, "Cross-site request rejected.") ErrLastSignInMethod = newErr("last_sign_in_method", http.StatusConflict, "You cannot remove your only sign-in method.") ErrInternal = newErr("internal_error", http.StatusInternalServerError, "Something went wrong.") ErrUnsupportedMediaType = newErr("unsupported_media_type", http.StatusUnsupportedMediaType, "Content-Type must be application/json.") )
Sentinel errors.
var DefaultRateLimits = map[string]ratelimit.Rule{ "signin:ip": {Limit: 50, Window: 15 * time.Minute}, "signin:account": {Limit: 10, Window: 15 * time.Minute}, "signup:ip": {Limit: 10, Window: time.Hour}, "email:send": {Limit: 5, Window: time.Hour}, "email:send:ip": {Limit: 20, Window: time.Hour}, "sms:send": {Limit: 5, Window: time.Hour}, "sms:send:ip": {Limit: 10, Window: time.Hour}, "otp:verify": {Limit: 10, Window: 15 * time.Minute}, "mfa:verify": {Limit: 10, Window: 15 * time.Minute}, "reauth": {Limit: 10, Window: 15 * time.Minute}, "anonymous:ip": {Limit: 20, Window: time.Hour}, "oauth:ip": {Limit: 60, Window: 15 * time.Minute}, "apikey:ip": {Limit: 600, Window: time.Minute}, "webauthn:ip": {Limit: 60, Window: 15 * time.Minute}, "saml:ip": {Limit: 60, Window: 15 * time.Minute}, "biometric:ip": {Limit: 120, Window: 15 * time.Minute}, "token:verify:ip": {Limit: 30, Window: 15 * time.Minute}, "exchange:ip": {Limit: 30, Window: 15 * time.Minute}, }
DefaultRateLimits are the built-in rate limit rules.
Functions ¶
func AnonymousUserID ¶
AnonymousUserID returns the user ID if u is a guest, else "".
func NormalizeEmail ¶
NormalizeEmail lower-cases and validates an email address.
func NormalizePhone ¶
NormalizePhone strips formatting and validates an E.164 phone number.
func UserFromContext ¶
UserFromContext returns the authenticated user, if any.
func ValidCodeChallenge ¶
ValidCodeChallenge reports whether c is a well-formed S256 PKCE challenge.
func WithActor ¶
WithActor records which administrator performs the operations made with ctx; it is written to admin_action events. transport/admin sets it.
func WithPrincipal ¶
WithPrincipal attaches p to ctx.
func WithRequestMeta ¶
func WithRequestMeta(ctx context.Context, m RequestMeta) context.Context
WithRequestMeta attaches request metadata to ctx. The REST and GraphQL handlers do this automatically; call it when using the Go API directly.
func WithSessionOptions ¶
func WithSessionOptions(ctx context.Context, o SessionOptions) context.Context
WithSessionOptions attaches options for sessions created with ctx.
func WriteError ¶
func WriteError(w http.ResponseWriter, err error)
WriteError writes a client-safe JSON error.
Types ¶
type APIKeyConfig ¶
type APIKeyConfig struct {
// Prefix is the visible key prefix. Default "ag".
Prefix string
// MaxTTL caps key lifetime. Zero means keys may be non-expiring.
MaxTTL time.Duration
// AllowedScopes restricts the scopes keys may carry. Empty allows any.
AllowedScopes []string
}
APIKeyConfig controls personal access tokens.
type APIKeyInput ¶
type APIKeyInput struct {
Name string
Scopes []string
ExpiresIn time.Duration // 0 = no expiry (unless APIKeys.MaxTTL is set)
}
APIKeyInput describes a new API key.
type APIKeyView ¶
type APIKeyView struct {
ID string `json:"id"`
Name string `json:"name"`
Prefix string `json:"prefix"` // shown to help users identify keys
Scopes []string `json:"scopes"`
ExpiresAt *time.Time `json:"expiresAt"`
LastUsedAt *time.Time `json:"lastUsedAt"`
RevokedAt *time.Time `json:"revokedAt"`
CreatedAt time.Time `json:"createdAt"`
}
APIKeyView is the client-facing view of an API key (never the secret).
type AccountView ¶
type AccountView struct {
ID string `json:"id"`
Provider string `json:"provider"`
Type string `json:"type"`
CreatedAt time.Time `json:"createdAt"`
}
AccountView is the client-facing view of a linked identity.
type AlertsConfig ¶
type AlertsConfig struct {
// DisableNewDevice turns off "new sign-in to your account" emails.
DisableNewDevice bool
// KnownDeviceTTL is how long a device stays recognized. Default 180 days.
KnownDeviceTTL time.Duration
}
AlertsConfig controls security notifications.
type AnonymousConfig ¶
type AnonymousConfig struct {
// TTL of inactivity after which unconverted guests are removed by
// Cleanup (guests with a session used within TTL are kept). Default 30 days.
TTL time.Duration
}
AnonymousConfig controls guest users.
type AuditConfig ¶
type AuditConfig struct {
// Enabled stores events in the audit_events table.
Enabled bool
// Skip lists event types not stored. Default: rate_limited, which
// unauthenticated clients can trigger at will. OnEvent still receives
// every event.
Skip []EventType
}
AuditConfig controls the built-in audit table.
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth is the authgen engine. It is safe for concurrent use.
func (*Auth) AccountTokens ¶
AccountTokens decrypts the stored provider tokens of a linked account (requires OAuth.StoreTokens). Use them to call provider APIs on behalf of the user.
func (*Auth) AdminDeleteUser ¶
AdminDeleteUser deletes a user.
func (*Auth) AdminResetMFA ¶
func (a *Auth) AdminResetMFA(ctx context.Context, actorID, userID string, includePasskeys bool) error
AdminResetMFA removes a user's second factors (authenticator app, email/SMS channels, recovery codes and, if includePasskeys, WebAuthn credentials) and signs out all their sessions. Use it for account recovery after verifying the user's identity out of band.
func (*Auth) AdminRevokeSessions ¶
AdminRevokeSessions signs a user out everywhere.
func (*Auth) AdminSetDisabled ¶
AdminSetDisabled disables (and signs out) or re-enables a user.
func (*Auth) Authenticate ¶
Authenticate resolves the request's principal from the session cookie, a bearer session token, or a bearer API key.
func (*Auth) AuthenticateAPIKey ¶
func (a *Auth) AuthenticateAPIKey(ctx context.Context, key string) (*store.APIKey, *store.User, error)
AuthenticateAPIKey validates an API key and returns it with its owner.
func (*Auth) BeginBiometricEnrollment ¶
func (a *Auth) BeginBiometricEnrollment(ctx context.Context, s *store.Session, u *store.User) (*BiometricChallenge, error)
BeginBiometricEnrollment returns a challenge for linking the signed-in user to their scanner identity. Requires a fresh session.
func (*Auth) BeginBiometricSignIn ¶
func (a *Auth) BeginBiometricSignIn(ctx context.Context) (*BiometricChallenge, error)
BeginBiometricSignIn returns a challenge for a scanner sign-in.
func (*Auth) BeginOAuth ¶
func (a *Auth) BeginOAuth(ctx context.Context, providerID string, opts OAuthStartOptions) (*OAuthStart, error)
BeginOAuth starts an OAuth/OIDC authorization-code flow with PKCE, state and nonce.
func (*Auth) BeginPasskeyLogin ¶
func (a *Auth) BeginPasskeyLogin(ctx context.Context) (options *protocol.CredentialAssertion, ceremonyID string, err error)
BeginPasskeyLogin starts a usernameless (discoverable credential) login. Returns the options for navigator.credentials.get() and a ceremony ID the client sends back to FinishPasskeyLogin.
func (*Auth) BeginPasskeyLoginWithOptions ¶
func (a *Auth) BeginPasskeyLoginWithOptions(ctx context.Context, o PasskeyLoginOptions) (options *protocol.CredentialAssertion, ceremonyID string, err error)
BeginPasskeyLoginWithOptions is BeginPasskeyLogin with options.
func (*Auth) BeginPasskeyRegistration ¶
func (a *Auth) BeginPasskeyRegistration(ctx context.Context, s *store.Session, u *store.User) (*protocol.CredentialCreation, error)
BeginPasskeyRegistration starts registering a passkey / security key for the signed-in user. Returns PublicKeyCredentialCreationOptions to pass to navigator.credentials.create(). Requires a fresh session.
func (*Auth) BeginTOTPEnrollment ¶
func (a *Auth) BeginTOTPEnrollment(ctx context.Context, s *store.Session, u *store.User) (*TOTPEnrollment, error)
BeginTOTPEnrollment generates a new TOTP secret (unconfirmed). Requires a fresh session.
func (*Auth) BeginWebAuthnMFA ¶
func (a *Auth) BeginWebAuthnMFA(ctx context.Context, challengeToken string) (*protocol.CredentialAssertion, error)
BeginWebAuthnMFA returns assertion options for completing a pending MFA challenge with a security key or passkey.
func (*Auth) BeginWebAuthnReauth ¶
func (a *Auth) BeginWebAuthnReauth(ctx context.Context, s *store.Session, u *store.User) (*protocol.CredentialAssertion, error)
BeginWebAuthnReauth returns assertion options for reauthenticating the current session with a passkey or security key.
func (*Auth) ChangePassword ¶
func (a *Auth) ChangePassword(ctx context.Context, s *store.Session, u *store.User, currentPassword, newPassword string) error
ChangePassword changes the password of a signed-in user. If the user already has a password, currentPassword must match; otherwise the session must be fresh. Other sessions are revoked.
func (*Auth) CheckCSRF ¶
CheckCSRF protects state-changing requests:
- Origin (or Sec-Fetch-Site) must be BaseURL's origin or a trusted origin.
- Requests authenticated by the session cookie must carry a valid double-submit token in X-CSRF-Token matching the CSRF cookie (unless CSRF.DisableToken). Bearer-token requests are exempt.
func (*Auth) CheckSchema ¶
CheckSchema verifies (read-only) that the database has every table and column authgen needs. Only available with the PostgreSQL store. Tables for disabled features are skipped.
func (*Auth) Cleanup ¶
func (a *Auth) Cleanup(ctx context.Context) (CleanupResult, error)
Cleanup deletes expired sessions and tokens, stale rate-limit counters, and guest users older than Anonymous.TTL. Run it periodically (e.g. hourly) from a cron job or a goroutine.
func (*Auth) ClearMFACookie ¶
func (a *Auth) ClearMFACookie(w http.ResponseWriter)
ClearMFACookie deletes the MFA challenge cookie.
func (*Auth) ClearOAuthCookie ¶
func (a *Auth) ClearOAuthCookie(w http.ResponseWriter)
ClearOAuthCookie expires the OAuth state cookie.
func (*Auth) ClearSAMLCookie ¶
func (a *Auth) ClearSAMLCookie(w http.ResponseWriter)
ClearSAMLCookie expires the SSO binding cookie.
func (*Auth) ClearSessionCookie ¶
func (a *Auth) ClearSessionCookie(w http.ResponseWriter)
ClearSessionCookie deletes the session cookie.
func (*Auth) ConfirmEmailChange ¶
ConfirmEmailChange applies an email change.
func (*Auth) ConfirmPhone ¶
func (a *Auth) ConfirmPhone(ctx context.Context, u *store.User, phone, code string) (*store.User, error)
ConfirmPhone verifies the code sent by RequestPhoneVerification.
func (*Auth) ConfirmTOTPEnrollment ¶
func (a *Auth) ConfirmTOTPEnrollment(ctx context.Context, s *store.Session, u *store.User, code string) (recoveryCodes []string, err error)
ConfirmTOTPEnrollment verifies the first code and activates TOTP. If this is the user's first factor, recovery codes are generated and returned (show them once). The session is upgraded to AAL2.
func (*Auth) ContextWithRequest ¶
ContextWithRequest returns ctx with metadata from r attached.
func (*Auth) CreateAPIKey ¶
func (a *Auth) CreateAPIKey(ctx context.Context, s *store.Session, u *store.User, in APIKeyInput) (*CreatedAPIKey, error)
CreateAPIKey creates a personal access token. Requires a fresh session.
func (*Auth) CreateExchangeCode ¶
func (a *Auth) CreateExchangeCode(ctx context.Context, res *AuthResult, codeChallenge string) (string, error)
CreateExchangeCode wraps the result of a redirect-based sign-in into a single-use code for a native app. codeChallenge is the app's S256 PKCE challenge.
func (*Auth) CreateSAMLConnection ¶
func (a *Auth) CreateSAMLConnection(ctx context.Context, in SAMLConnectionInput) (*store.SAMLConnection, error)
CreateSAMLConnection registers an organization's IdP. This is an admin operation: expose it only to trusted administrators.
func (*Auth) DeletePasskey ¶
DeletePasskey removes a credential. Requires a fresh session and refuses to remove the user's last way to sign in.
func (*Auth) DeleteSAMLConnection ¶
DeleteSAMLConnection removes a connection.
func (*Auth) DeleteUser ¶
DeleteUser permanently deletes a user and (via cascades) all their data.
func (*Auth) DisableMFAChannel ¶
func (a *Auth) DisableMFAChannel(ctx context.Context, s *store.Session, u *store.User, channel string) error
DisableMFAChannel removes email or SMS codes as a second factor.
func (*Auth) DisableTOTP ¶
DisableTOTP removes the authenticator app. Requires a fresh session.
func (*Auth) DisableUser ¶
DisableUser blocks a user from signing in and revokes their sessions.
func (*Auth) EnableMFAChannel ¶
func (a *Auth) EnableMFAChannel(ctx context.Context, s *store.Session, u *store.User, channel string) ([]string, error)
EnableMFAChannel enables email or SMS codes as a second factor. The email/phone must already be verified. Requires a fresh session. Returns recovery codes if this is the first factor.
func (*Auth) EnableUser ¶
EnableUser re-enables a disabled user.
func (*Auth) ExchangeCode ¶
ExchangeCode redeems a code from CreateExchangeCode. verifier is the PKCE code_verifier. The result carries either a session (with its token) or a pending MFA challenge.
func (*Auth) FinishBiometricEnrollment ¶
func (a *Auth) FinishBiometricEnrollment(ctx context.Context, s *store.Session, u *store.User, assertion string) error
FinishBiometricEnrollment links the scanner subject in the assertion to the signed-in user.
func (*Auth) FinishPasskeyLogin ¶
func (a *Auth) FinishPasskeyLogin(ctx context.Context, ceremonyID string, response []byte) (*AuthResult, error)
FinishPasskeyLogin verifies the assertion and signs the user in. User verification is required, so the session starts at AAL2 without a separate second factor.
func (*Auth) FinishPasskeyRegistration ¶
func (a *Auth) FinishPasskeyRegistration(ctx context.Context, s *store.Session, u *store.User, name string, response []byte) (*PasskeyRegistration, error)
FinishPasskeyRegistration verifies the attestation response (JSON from navigator.credentials.create()) and stores the credential. Guest users become regular users with a passkey.
func (*Auth) GetUserDetails ¶
GetUserDetails returns everything authgen knows about a user (no secrets).
func (*Auth) HandleOAuthCallback ¶
func (a *Auth) HandleOAuthCallback(ctx context.Context, providerID string, r *http.Request) (*OAuthOutcome, error)
HandleOAuthCallback completes the flow. r is the callback request (GET query or form_post body).
func (*Auth) HandleSAMLACS ¶
func (a *Auth) HandleSAMLACS(ctx context.Context, connectionID string, r *http.Request) (*SAMLOutcome, error)
HandleSAMLACS validates a SAML response posted to the ACS endpoint and signs the user in (JIT-provisioning new users).
func (*Auth) HandleSAMLLogoutResponse ¶
func (a *Auth) HandleSAMLLogoutResponse(ctx context.Context, connectionID string, r *http.Request) error
HandleSAMLLogoutResponse validates the IdP's LogoutResponse (the end of SP-initiated single logout). IdP-initiated logout requests are not supported; sessions end through authgen's own expiry and revocation.
func (*Auth) IsNativeRedirect ¶
IsNativeRedirect reports whether raw matches one of Config.NativeRedirectURIs (same scheme and host, path prefix).
func (*Auth) IsSafeRedirect ¶
IsSafeRedirect reports whether raw is an allowed post-auth redirect: a same-site relative path, or an absolute URL on BaseURL's origin or a trusted origin. Prevents open redirects.
func (*Auth) IsTrustedOrigin ¶
IsTrustedOrigin reports whether origin may make credentialed requests.
func (*Auth) LinkBiometricSubject ¶
LinkBiometricSubject links a scanner subject to a user directly, e.g. during HR onboarding where identity was checked in person. Administrative: expose only to trusted operators.
func (*Auth) ListAPIKeys ¶
ListAPIKeys lists a user's API keys.
func (*Auth) ListAccounts ¶
ListAccounts returns the user's linked identities.
func (*Auth) ListAuditEvents ¶
func (a *Auth) ListAuditEvents(ctx context.Context, q store.AuditQuery) ([]*store.AuditEvent, error)
ListAuditEvents returns stored audit events (requires Audit.Enabled).
func (*Auth) ListPasskeys ¶
ListPasskeys returns the user's WebAuthn credentials.
func (*Auth) ListSAMLConnections ¶
ListSAMLConnections lists connections.
func (*Auth) ListSessions ¶
ListSessions returns the user's active sessions.
func (*Auth) MFAChallengeFromRequest ¶
MFAChallengeFromRequest returns the challenge token from the MFA cookie.
func (*Auth) MFAEnrollmentRequired ¶
MFAEnrollmentRequired reports whether policy (MFA.Require / MFA.RequireFor) obliges u to enroll a second factor before using the application.
func (*Auth) MFAMethods ¶
MFAMethods returns the second-factor methods available to a user.
func (*Auth) MetaFromRequest ¶
func (a *Auth) MetaFromRequest(r *http.Request) RequestMeta
MetaFromRequest extracts RequestMeta from an HTTP request, honoring TrustProxyHeaders.
func (*Auth) Middleware ¶
Middleware authenticates requests when credentials are present and attaches the Principal to the context. Unauthenticated requests pass through (combine with the Require* middlewares); cookie-authenticated, state-changing requests that fail the CSRF check are rejected with 403.
func (*Auth) NewCSRFToken ¶
func (a *Auth) NewCSRFToken(w http.ResponseWriter) string
NewCSRFToken returns a signed CSRF token and sets it as a cookie. The client must echo the token in the X-CSRF-Token header on state-changing cookie-authenticated requests.
func (*Auth) PrepareRequest ¶
PrepareRequest returns ctx with request metadata attached and makes sure browsers carry a long-lived device cookie (used for new-device alerts). The REST and GraphQL handlers call it for every request.
func (*Auth) Reauthenticate ¶
func (a *Auth) Reauthenticate(ctx context.Context, s *store.Session, u *store.User, in ReauthInput) (string, error)
Reauthenticate refreshes the session's authentication time (and AAL when a second factor is used) and rotates the session token. Returns the new session token.
func (*Auth) RecoveryCodesRemaining ¶
RecoveryCodesRemaining returns the number of unused recovery codes.
func (*Auth) RegenerateRecoveryCodes ¶
func (a *Auth) RegenerateRecoveryCodes(ctx context.Context, s *store.Session, u *store.User) ([]string, error)
RegenerateRecoveryCodes replaces all recovery codes. Requires MFA to be enrolled and a fresh session.
func (*Auth) RenamePasskey ¶
RenamePasskey renames a credential.
func (*Auth) RequestEmailChange ¶
func (a *Auth) RequestEmailChange(ctx context.Context, s *store.Session, u *store.User, newEmail string) error
RequestEmailChange sends a confirmation link to a new email address. Requires a fresh session.
func (*Auth) RequestEmailOTP ¶
RequestEmailOTP emails a one-time sign-in code.
func (*Auth) RequestMagicLink ¶
RequestMagicLink emails a single-use sign-in link. It always returns nil for valid input to avoid account enumeration. Accounts are created on first successful verification.
func (*Auth) RequestMagicLinkWithOptions ¶
func (a *Auth) RequestMagicLinkWithOptions(ctx context.Context, o MagicLinkOptions) error
RequestMagicLinkWithOptions is RequestMagicLink with native-app and session options.
func (*Auth) RequestPasswordReset ¶
RequestPasswordReset emails a reset link if the account exists. It always returns nil (unless rate limited by IP) to avoid enumeration.
func (*Auth) RequestPhoneVerification ¶
func (a *Auth) RequestPhoneVerification(ctx context.Context, s *store.Session, u *store.User, phone string) error
RequestPhoneVerification texts a code to add or change the phone number of a signed-in user. Requires a fresh session.
func (*Auth) RequestSMSOTP ¶
RequestSMSOTP texts a one-time sign-in code to a phone number (E.164).
func (*Auth) RequireAPIKey ¶
RequireAPIKey accepts only API keys carrying all the given scopes.
func (*Auth) RequireFresh ¶
RequireFresh returns ErrReauthRequired unless the session recently authenticated (and passed MFA if the user has it enrolled).
func (*Auth) RequireFreshSession ¶
RequireFreshSession rejects sessions that have not authenticated within Session.FreshAge (clients should call /auth/reauthenticate).
func (*Auth) RequireMFA ¶
RequireMFA rejects sessions below AAL2 (second factor not verified).
func (*Auth) RequireSession ¶
RequireSession rejects requests without a (non-guest) user session. API keys are not accepted.
func (*Auth) RequireUser ¶
RequireUser rejects requests without a session or API key.
func (*Auth) ResetPassword ¶
ResetPassword sets a new password using a reset token. All sessions are revoked and MFA is still required at the next sign-in; the email second factor is suspended for EmailFactorLockout because the reset itself used the inbox. Resetting an unverified account claims it for the inbox owner.
func (*Auth) ResolveRedirect ¶
ResolveRedirect returns an absolute redirect target, falling back to fallback (or "/") when raw is empty or unsafe.
func (*Auth) RevokeAPIKey ¶
RevokeAPIKey revokes one of the user's API keys.
func (*Auth) RevokeOtherSessions ¶
RevokeOtherSessions deletes all of the user's sessions except keepID.
func (*Auth) RevokeSession ¶
RevokeSession deletes one of the user's sessions.
func (*Auth) SAMLLogoutURL ¶
SAMLLogoutURL returns the IdP single-logout URL for a session that was created through SAML SSO, or "" when not applicable (non-SAML session, or the IdP has no HTTP-Redirect SLO endpoint). Call it before signing out.
func (*Auth) SAMLMetadata ¶
SAMLMetadata returns this service provider's metadata XML for a connection, to be uploaded to the IdP.
func (*Auth) SendMFACode ¶
SendMFACode sends an email or SMS code for a pending challenge.
func (*Auth) SendReauthCode ¶
func (a *Auth) SendReauthCode(ctx context.Context, s *store.Session, u *store.User, channel string) error
SendReauthCode sends an email/SMS code for reauthentication to any verified contact (useful for passwordless users).
func (*Auth) SendVerificationEmail ¶
SendVerificationEmail (re)sends the verification email. It always succeeds from the caller's perspective to avoid account enumeration.
func (*Auth) SessionCookieName ¶
SessionCookieName returns the session cookie name.
func (*Auth) SessionFromRequest ¶
SessionFromRequest validates the session carried by r.
func (*Auth) SessionPayload ¶
func (a *Auth) SessionPayload(ctx context.Context, s *store.Session, u *store.User) (map[string]any, error)
SessionPayload builds the /session response, applying Callbacks.Session.
func (*Auth) SetMFACookie ¶
func (a *Auth) SetMFACookie(w http.ResponseWriter, p *MFAPending)
SetMFACookie stores a pending MFA challenge in an HttpOnly cookie, used by redirect-based flows (OAuth, SAML, magic links).
func (*Auth) SetSessionCookie ¶
func (a *Auth) SetSessionCookie(w http.ResponseWriter, is *IssuedSession)
SetSessionCookie writes the session cookie for an issued session.
func (*Auth) SetSessionToken ¶
SetSessionToken writes the session cookie for a rotated token.
func (*Auth) Shutdown ¶
Shutdown waits for background email/SMS deliveries to finish (or ctx to end). Call it during graceful shutdown.
func (*Auth) SignInAnonymously ¶
func (a *Auth) SignInAnonymously(ctx context.Context) (*IssuedSession, error)
SignInAnonymously creates a guest user and session. Guests can later be upgraded (keeping their user ID) by signing up with a password, verifying an email/SMS code or magic link, completing OAuth, or registering a passkey while the guest session is active.
func (*Auth) SignInWithBiometric ¶
SignInWithBiometric signs in the person a scanner recognized. The usual MFA policy applies; a scan on a shared scanner is one factor (AAL1).
func (*Auth) SignInWithPassword ¶
SignInWithPassword authenticates with email and password.
func (*Auth) SignUp ¶
func (a *Auth) SignUp(ctx context.Context, in SignUpInput) (*SignUpResult, error)
SignUp registers a user with email and password.
func (*Auth) TakeSAMLPostForm ¶
TakeSAMLPostForm consumes a stashed POST-binding request.
func (*Auth) TokenFromRequest ¶
TokenFromRequest returns the session token from the Authorization bearer header or the session cookie. fromCookie reports where it came from.
func (*Auth) UnlinkAccount ¶
func (a *Auth) UnlinkAccount(ctx context.Context, s *store.Session, u *store.User, accountID string) error
UnlinkAccount removes a linked identity. Requires a fresh session and refuses to remove the last way to sign in.
func (*Auth) UpdateProfile ¶
func (a *Auth) UpdateProfile(ctx context.Context, userID string, p ProfileUpdate) (*store.User, error)
UpdateProfile changes non-security profile fields.
func (*Auth) UpdateSAMLConnection ¶
func (a *Auth) UpdateSAMLConnection(ctx context.Context, id string, in SAMLConnectionInput) (*store.SAMLConnection, error)
UpdateSAMLConnection replaces a connection's settings.
func (*Auth) ValidateSession ¶
func (a *Auth) ValidateSession(ctx context.Context, token string) (*store.Session, *store.User, error)
ValidateSession resolves a session token. Expired, idle or disabled-user sessions are rejected (and expired ones deleted).
func (*Auth) VerifyEmail ¶
VerifyEmail consumes an email verification token. Opening the link on the device that signed up is enough; on any other device the account's password must be supplied (ErrPasswordRequired otherwise, and the token stays valid). This stops a victim who clicks a link for an account they never created from activating the attacker's password.
func (*Auth) VerifyEmailOTP ¶
func (a *Auth) VerifyEmailOTP(ctx context.Context, email, code, anonymousUserID string) (*AuthResult, error)
VerifyEmailOTP checks an email sign-in code and signs the user in.
func (*Auth) VerifyMFA ¶
func (a *Auth) VerifyMFA(ctx context.Context, in MFAVerifyInput) (*IssuedSession, error)
VerifyMFA completes a challenge and issues an AAL2 session.
func (*Auth) VerifyMagicLink ¶
func (a *Auth) VerifyMagicLink(ctx context.Context, token, anonymousUserID string) (*MagicLinkOutcome, error)
VerifyMagicLink consumes a magic-link token and signs the user in. The outcome carries the validated callbackUrl requested when the link was sent.
func (*Auth) VerifySMSOTP ¶
func (a *Auth) VerifySMSOTP(ctx context.Context, phone, code, anonymousUserID string) (*AuthResult, error)
VerifySMSOTP checks an SMS sign-in code and signs the user in.
type AuthResult ¶
type AuthResult struct {
Session *IssuedSession
MFA *MFAPending
User *store.User
// MFAEnrollmentRequired is set when policy requires MFA and the user
// has no second factor yet: the session only allows enrollment.
MFAEnrollmentRequired bool
}
AuthResult is the outcome of a first-factor sign-in: either a session or a pending MFA challenge.
type BiometricChallenge ¶
type BiometricChallenge struct {
Nonce string `json:"nonce"`
ExpiresAt time.Time `json:"expiresAt"`
}
BiometricChallenge is a single-use challenge for a scanner.
type BiometricConfig ¶
type BiometricConfig struct {
// Verifier checks scanner match tokens, e.g. biometric.NewJWTVerifier.
Verifier biometric.Verifier
// ID names this scanner system; linked accounts use provider
// "biometric:<ID>". Default "scanner".
ID string
// ChallengeTTL bounds the time between challenge and scan. Default 2 minutes.
ChallengeTTL time.Duration
}
BiometricConfig connects dedicated scanners (see package biometric). authgen never receives biometric data, only signed match results.
type BotProtectionConfig ¶
type BotProtectionConfig struct {
// Verifier checks tokens (captcha.Turnstile, captcha.HCaptcha,
// captcha.ReCaptchaV3, or your own). Nil disables bot protection.
Verifier captcha.Verifier
// Actions to protect. Default: signup, password_forgot, magic_link,
// email_otp, sms_otp, anonymous, verify_resend. Add "signin" to also
// protect password sign-in.
Actions []string
// FailOpen allows the action when the CAPTCHA provider is unreachable.
// By default authgen fails closed.
FailOpen bool
}
BotProtectionConfig requires CAPTCHA tokens (X-Captcha-Token header) for abuse-prone actions.
type CSRFConfig ¶
type CSRFConfig struct {
// DisableToken disables the double-submit token requirement. Origin /
// Fetch-Metadata checks always apply.
DisableToken bool
}
CSRFConfig controls CSRF protection for cookie-authenticated requests.
type Callbacks ¶
type Callbacks struct {
// SignIn is called before a session is created. Return an error to deny.
SignIn func(ctx context.Context, attempt SignInAttempt) error
// Session customizes the session view returned to clients.
Session func(ctx context.Context, user *store.User, session *store.Session, view map[string]any)
}
Callbacks customize authgen decisions.
type CleanupResult ¶
type CleanupResult struct {
Sessions int64
VerificationTokens int64
AnonymousUsers int64
RateLimits int64
}
CleanupResult reports what Cleanup removed.
type Config ¶
type Config struct {
// Pool is the application's PostgreSQL pool. authgen only runs DML on
// it, never DDL.
Pool *pgxpool.Pool
// Store overrides the storage backend (e.g. memstore in tests). When
// set, Pool and Schema are ignored.
Store store.Store
// Schema maps authgen's tables/columns onto the application's names.
Schema schema.Mapping
// BaseURL is the public URL where the authgen REST handler is mounted,
// e.g. "https://api.example.com/auth". Used to build callback and
// email links.
BaseURL string
// Secrets are master secrets (>= 32 bytes each). The first one is used
// for new values; the others are accepted for rotation.
Secrets []string
// AppName is shown in authenticator apps, passkey prompts and emails.
AppName string
// TrustedOrigins are the frontend origins (scheme://host[:port]) allowed
// to make credentialed requests and to be used as redirect targets.
TrustedOrigins []string
// URLs are frontend pages authgen redirects to or links to in emails.
URLs URLs
// Methods enables sign-in methods. OAuth is enabled by configuring providers.
Methods Methods
Session SessionConfig
Password PasswordConfig
Tokens TokenConfig
MFA MFAConfig
OAuth OAuthConfig
WebAuthn WebAuthnConfig
SAML SAMLConfig
Biometric BiometricConfig
APIKeys APIKeyConfig
Anonymous AnonymousConfig
RateLimit RateLimitConfig
CSRF CSRFConfig
// Email and SMS deliver messages through the application's providers.
Email notify.EmailSender
SMS notify.SMSSender
// SMSPolicy limits SMS abuse (toll fraud / SMS pumping).
SMSPolicy SMSPolicyConfig
// Templates customize email/SMS content (and translate it).
Templates Templates
// BotProtection requires a CAPTCHA token for abuse-prone actions.
BotProtection BotProtectionConfig
// Alerts configures security notifications to users.
Alerts AlertsConfig
// NativeRedirectURIs allow native/mobile apps to receive the result of
// redirect-based flows (OAuth, SAML, magic links). Each entry is a URI
// prefix such as "com.example.app:/auth". A callbackUrl matching one of
// them receives a short-lived, single-use code (never a cookie) that the
// app redeems at POST /auth/token/exchange with its PKCE code_verifier.
NativeRedirectURIs []string
// SyncNotifications delivers emails/SMS synchronously. By default they
// are sent in the background (see Auth.Shutdown) so that response times
// do not reveal whether an account exists.
SyncNotifications bool
// Audit stores every event in the audit_events table, in addition to OnEvent.
Audit AuditConfig
Callbacks Callbacks
// OnEvent receives audit/security events. It is called synchronously;
// do slow work asynchronously.
OnEvent func(ctx context.Context, e Event)
// TrustProxyHeaders derives the client IP from X-Forwarded-For. Proxies
// append to that header, so the client controls its leftmost entries;
// authgen walks it from the right instead (see TrustedProxyHops and
// TrustedProxies). X-Real-IP is used only when X-Forwarded-For is
// absent, so only trust it behind a proxy that overwrites it.
TrustProxyHeaders bool
// TrustedProxyHops is the number of proxies in front of the app that
// append to X-Forwarded-For (default 1: e.g. a single load balancer).
TrustedProxyHops int
// TrustedProxies lists proxy CIDRs (e.g. "10.0.0.0/8"). When set, the
// headers are honored only for requests from these addresses, and the
// client IP is the rightmost X-Forwarded-For entry outside them.
TrustedProxies []string
// HTTPClient is used for outbound calls (OAuth, HIBP). Default has a 10s timeout.
HTTPClient *http.Client
Logger *slog.Logger
// Now overrides the clock (tests).
Now func() time.Time
}
Config configures authgen. Pool (or Store), BaseURL and Secrets are required.
type CreatedAPIKey ¶
type CreatedAPIKey struct {
Key string `json:"key"`
View APIKeyView `json:"apiKey"`
}
CreatedAPIKey holds a new key. Key is shown once and never stored.
type Error ¶
type Error struct {
Code string
Status int
Message string
RetryAfter time.Duration
// contains filtered or unexported fields
}
Error is a client-safe error with a stable machine-readable code. Messages never reveal whether an account exists.
func AsError ¶
AsError converts any error into a client-safe *Error. Unknown errors become ErrInternal (details are kept only in the cause for logging).
type ErrorBody ¶
type ErrorBody struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
ErrorBody is the JSON error envelope.
type Event ¶
type Event struct {
Type EventType
Time time.Time
UserID string
SessionID string
Method string
IP string
UserAgent string
Metadata map[string]any
}
Event is an audit/security event.
type EventType ¶
type EventType string
EventType identifies an audit/security event.
const ( EventSignIn EventType = "sign_in" EventSignInFailed EventType = "sign_in_failed" EventSignOut EventType = "sign_out" EventUserCreated EventType = "user_created" EventUserUpdated EventType = "user_updated" EventUserDeleted EventType = "user_deleted" EventEmailVerified EventType = "email_verified" EventPhoneVerified EventType = "phone_verified" EventPasswordChanged EventType = "password_changed" EventPasswordReset EventType = "password_reset" EventAccountLinked EventType = "account_linked" EventAccountUnlinked EventType = "account_unlinked" EventMFAEnrolled EventType = "mfa_enrolled" EventMFARemoved EventType = "mfa_removed" EventMFAVerified EventType = "mfa_verified" EventMFAFailed EventType = "mfa_failed" EventRecoveryCodeUsed EventType = "recovery_code_used" EventRecoveryRegenerate EventType = "recovery_codes_regenerated" EventSessionRevoked EventType = "session_revoked" EventPasskeyAdded EventType = "passkey_added" EventPasskeyRemoved EventType = "passkey_removed" EventAPIKeyCreated EventType = "api_key_created" EventAPIKeyRevoked EventType = "api_key_revoked" EventAnonymousUpgraded EventType = "anonymous_upgraded" EventRateLimited EventType = "rate_limited" EventSuspicious EventType = "suspicious_activity" EventNewDevice EventType = "new_device_sign_in" EventAdminAction EventType = "admin_action" )
type HIBPChecker ¶
type HIBPChecker struct {
Client *http.Client
BaseURL string // default https://api.pwnedpasswords.com/range/
}
HIBPChecker queries the Have I Been Pwned range API using k-anonymity: only the first 5 hex characters of the SHA-1 hash leave the server, and response padding is requested.
func (*HIBPChecker) IsBreached ¶
IsBreached implements PasswordChecker.
type IssuedSession ¶
IssuedSession is a newly created session. Token is the bearer secret; it is never stored and cannot be recovered later.
type MFAConfig ¶
type MFAConfig struct {
// Issuer shown in authenticator apps. Default AppName.
Issuer string
// RecoveryCodeCount is the number of recovery codes. Default 10.
RecoveryCodeCount int
// ChallengeTTL is how long a pending MFA challenge is valid. Default 10 minutes.
ChallengeTTL time.Duration
// MaxAttempts per challenge. Default 5.
MaxAttempts int
// DisableEmail / DisableSMS remove email/SMS codes as second factors.
// SMS is never phishing-resistant; prefer TOTP or WebAuthn.
DisableEmail bool
DisableSMS bool
// Require enforces MFA for every (non-guest) user. Users without a
// second factor can still sign in, but their sessions are limited to
// MFA enrollment: the Require* middlewares answer
// "mfa_enrollment_required" until a factor is enrolled.
Require bool
// RequireFor enforces MFA for selected users (e.g. admins). It is
// consulted in addition to Require.
RequireFor func(ctx context.Context, u *store.User) bool
}
MFAConfig controls multi-factor authentication.
type MFAPending ¶
MFAPending describes a second-factor challenge the client must complete via VerifyMFA.
type MFAVerifyInput ¶
type MFAVerifyInput struct {
ChallengeToken string
Method string // totp, recovery_code, email, sms, webauthn
Code string
// WebAuthnResponse is the JSON PublicKeyCredential from navigator.credentials.get().
WebAuthnResponse []byte
}
MFAVerifyInput completes a pending MFA challenge.
type MagicLinkOptions ¶
type MagicLinkOptions struct {
Email string
CallbackURL string
// CodeChallenge is a native app's S256 PKCE challenge (required when
// CallbackURL is a native redirect URI).
CodeChallenge string
// Ephemeral creates a "remember me: off" session.
Ephemeral bool
}
MagicLinkOptions configures RequestMagicLinkWithOptions.
type MagicLinkOutcome ¶
type MagicLinkOutcome struct {
Result *AuthResult
CallbackURL string
CodeChallenge string
}
MagicLinkOutcome is the result of VerifyMagicLink.
type Methods ¶
type Methods struct {
Password bool // email + password
MagicLink bool // email magic link
EmailOTP bool // email one-time code sign-in
SMSOTP bool // phone one-time code sign-in
Passkey bool // passwordless WebAuthn sign-in (requires WebAuthn config)
Anonymous bool // guest sessions
APIKeys bool // personal access tokens
SAML bool // enterprise SSO (requires SAML config)
Biometric bool // dedicated fingerprint/iris/face scanners (requires Biometric.Verifier)
}
Methods enables sign-in methods.
type OAuthConfig ¶
type OAuthConfig struct {
Providers []*oauth.Provider
// StoreTokens keeps provider tokens (encrypted) in the accounts table.
// AccountTokens refreshes expired access tokens automatically.
StoreTokens bool
// AllowEmailLinking links a new OAuth identity to an existing user with
// the same email when the provider vouches for the email
// (TrustEmailVerified and email_verified). Off by default, like
// Auth.js: users must sign in first and link from their settings,
// which protects against compromised or misconfigured providers.
AllowEmailLinking bool
// StateTTL bounds the time between sign-in start and callback. Default 10 minutes.
StateTTL time.Duration
}
OAuthConfig configures OAuth / OIDC providers.
type OAuthOutcome ¶
type OAuthOutcome struct {
Result *AuthResult // nil when linking or on error
Linked bool
CallbackURL string
// CodeChallenge is set for native-app flows (see CreateExchangeCode).
CodeChallenge string
}
OAuthOutcome is the result of an OAuth callback. When HandleOAuthCallback fails after the state was validated, it still returns an outcome carrying CallbackURL/CodeChallenge so errors can be reported to native apps.
type OAuthStart ¶
OAuthStart is the redirect to the provider plus the state cookie the caller must set on the response.
type OAuthStartOptions ¶
type OAuthStartOptions struct {
// CallbackURL is where to send the browser after sign-in (validated).
CallbackURL string
// LinkUserID links the identity to this signed-in user instead of signing in.
LinkUserID string
// AnonymousUserID upgrades this guest user if the identity is new.
AnonymousUserID string
// CodeChallenge is the S256 PKCE challenge of a native app; required
// when CallbackURL is a native redirect URI (see NativeRedirectURIs).
CodeChallenge string
// Ephemeral creates a "remember me: off" session.
Ephemeral bool
}
OAuthStartOptions configures BeginOAuth.
type PasskeyLoginOptions ¶
type PasskeyLoginOptions struct {
// Conditional requests conditional mediation (passkey autofill in the
// username field: <input autocomplete="username webauthn">).
Conditional bool
}
PasskeyLoginOptions configures BeginPasskeyLoginWithOptions.
type PasskeyRegistration ¶
type PasskeyRegistration struct {
Passkey PasskeyView
RecoveryCodes []string // set when this is the user's first second factor
}
PasskeyRegistration is the result of FinishPasskeyRegistration.
type PasskeyView ¶
type PasskeyView struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"createdAt"`
LastUsedAt *time.Time `json:"lastUsedAt"`
BackupEligible bool `json:"backupEligible"` // synced passkey
BackedUp bool `json:"backedUp"`
Transports []string `json:"transports"`
}
PasskeyView is the client-facing view of a WebAuthn credential.
type PasswordChecker ¶
PasswordChecker reports whether a password is known to be compromised.
type PasswordCheckerFunc ¶
PasswordCheckerFunc adapts a function to PasswordChecker.
func (PasswordCheckerFunc) IsBreached ¶
type PasswordConfig ¶
type PasswordConfig struct {
MinLength int // default 8
MaxLength int // default 128
Argon2 secure.Argon2Params
// Checker rejects compromised passwords. Default: Have I Been Pwned
// k-anonymity API (fails open on network errors).
Checker PasswordChecker
// DisableBreachCheck turns off the default breach checker.
DisableBreachCheck bool
// BreachCheckFailClosed rejects passwords (with 503) when the breach
// checker is unreachable. By default the check fails open.
BreachCheckFailClosed bool
// AllowUnverifiedSignIn lets users sign in before verifying their email.
// When false (default) sign-up never creates a session, so the
// response does not reveal whether the email was already registered.
AllowUnverifiedSignIn bool
}
PasswordConfig controls password policy and hashing.
type Principal ¶
type Principal struct {
User *store.User
Session *store.Session // nil for API-key requests
APIKey *store.APIKey // nil for session requests
// Token is the raw session token (used internally for rotation).
Token string
// MFAEnrollmentRequired is true when policy requires MFA and this
// session's user has not enrolled a factor yet. The Require*
// middlewares reject such sessions; check it if you only use
// Middleware.
MFAEnrollmentRequired bool
}
Principal is the authenticated caller of a request: a user with either a session or an API key.
type ProfileUpdate ¶
ProfileUpdate holds optional profile changes.
type RateLimitConfig ¶
type RateLimitConfig struct {
// Disabled turns rate limiting off (tests only).
Disabled bool
// FailOpen allows requests when the limiter's store errors. By default
// authgen fails closed (503) so an outage cannot disable throttling.
FailOpen bool
// Limiter overrides the store-backed limiter.
Limiter ratelimit.Limiter
// Rules overrides default rules by name (see DefaultRateLimits).
Rules map[string]ratelimit.Rule
}
RateLimitConfig controls throttling.
type ReauthInput ¶
type ReauthInput struct {
// Method is "password" or an MFA method (totp, recovery_code, email, sms, webauthn).
Method string
Password string
Code string
WebAuthnResponse []byte
}
ReauthInput proves the user's identity again for sensitive operations.
type RequestMeta ¶
type RequestMeta struct {
IP string
UserAgent string
// Origin of the request (for WebAuthn), if known.
Origin string
// CaptchaToken is the bot-protection token (X-Captcha-Token header).
CaptchaToken string
// Locale is the preferred language (first Accept-Language tag), passed
// to message templates.
Locale string
// DeviceID identifies the client device for new-device alerts (the
// device cookie, or the X-Device-Id header for native apps).
DeviceID string
}
RequestMeta carries client information used for sessions, rate limits and audit events.
type SAMLConfig ¶
type SAMLConfig struct {
// Certificate and PrivateKey (PEM) identify this service provider.
Certificate string
PrivateKey string
// AllowIdPInitiated accepts unsolicited responses. Off by default
// because IdP-initiated SSO is vulnerable to login CSRF.
AllowIdPInitiated bool
// AllowEmailLinking lets a connection's IdP sign in EXISTING verified
// users whose email is within the connection's domains. Off by default:
// whoever can create a connection (an administrator, or a stolen admin
// session) could otherwise point a domain at their own IdP and sign in
// as its users. New users are always provisioned.
AllowEmailLinking bool
// EmailAttributes are attribute names checked for the email address
// before falling back to the NameID. Default common names.
EmailAttributes []string
}
SAMLConfig configures the SAML service provider.
type SAMLConnectionInput ¶
type SAMLConnectionInput struct {
OrgID string
Domains []string // email domains routed to this IdP
IdPMetadataXML string
Enabled bool
}
SAMLConnectionInput creates or updates a SAML connection.
type SAMLOutcome ¶
type SAMLOutcome struct {
Result *AuthResult
CallbackURL string
CodeChallenge string
}
SAMLOutcome is the result of an ACS request.
type SAMLPostForm ¶
type SAMLPostForm struct {
URL string `json:"url"`
SAMLRequest string `json:"samlRequest"`
RelayState string `json:"relayState"`
}
SAMLPostForm is an AuthnRequest for IdPs that only accept the HTTP-POST binding. The browser must POST SAMLRequest and RelayState to URL.
type SAMLStart ¶
BeginSAML starts SP-initiated SSO and returns the IdP redirect URL. SAMLStart is the IdP redirect plus a browser-binding cookie the caller must set on the response. The ACS only honors the request (its callbackUrl, guest upgrade and native PKCE challenge) when the response is posted by the browser that carries this cookie, which prevents SSO login CSRF and "complete my sign-in" hijacks.
type SAMLStartOptions ¶
type SAMLStartOptions struct {
Email string // routes by email domain
ConnectionID string // or explicit connection
CallbackURL string
// AnonymousUserID upgrades this guest user if the identity is new.
AnonymousUserID string
// CodeChallenge is a native app's S256 PKCE challenge (required when
// CallbackURL is a native redirect URI).
CodeChallenge string
// Ephemeral creates a "remember me: off" session.
Ephemeral bool
}
SAMLStartOptions selects the connection for SP-initiated SSO.
type SMSPolicyConfig ¶
type SMSPolicyConfig struct {
// AllowedCountryCodes restricts destinations to E.164 prefixes such as
// "+1" or "+44". Empty allows all countries (not recommended: SMS
// pumping fraud targets premium-rate destinations).
AllowedCountryCodes []string
// DailyLimit caps SMS messages per 24 hours across the whole
// deployment. Default 1000; negative disables the cap.
DailyLimit int
}
SMSPolicyConfig limits where and how many SMS messages are sent.
type SessionConfig ¶
type SessionConfig struct {
// AbsoluteTTL is the maximum session lifetime. Default 30 days.
AbsoluteTTL time.Duration
// IdleTTL expires sessions not used for this long. Default 7 days.
IdleTTL time.Duration
// TouchInterval limits last-seen writes. Default 5 minutes.
TouchInterval time.Duration
// FreshAge is how recently the user must have authenticated to perform
// sensitive operations (change password, manage MFA, API keys). Default 10 minutes.
FreshAge time.Duration
// CookieName overrides the session cookie name. Default
// "__Host-authgen.session" (or "authgen.session" with InsecureCookies).
CookieName string
// CookieDomain shares the cookie with subdomains. Disables the __Host- prefix.
CookieDomain string
// SameSite for the session cookie. Default Lax.
SameSite http.SameSite
// InsecureCookies drops the Secure flag. Local HTTP development only.
InsecureCookies bool
// RevokeOthersOnPasswordChange signs out other sessions. Default true
// (set KeepOthersOnPasswordChange to disable).
KeepOthersOnPasswordChange bool
// EphemeralTTL is the lifetime of sessions created with "remember me"
// off (see WithSessionOptions). Their cookie has no Max-Age, so it is
// dropped when the browser closes. Default 12 hours.
EphemeralTTL time.Duration
}
SessionConfig controls sessions and cookies.
type SessionOptions ¶
type SessionOptions struct {
// Ephemeral ("remember me" off) limits the session to
// Session.EphemeralTTL and makes the cookie a browser-session cookie.
Ephemeral bool
}
SessionOptions customize the session created by a sign-in.
type SessionView ¶
type SessionView struct {
ID string `json:"id"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
LastSeenAt time.Time `json:"lastSeenAt"`
AuthenticatedAt time.Time `json:"authenticatedAt"`
IP *string `json:"ip"`
UserAgent *string `json:"userAgent"`
AAL int `json:"aal"`
AMR []string `json:"amr"`
MFAVerifiedAt *time.Time `json:"mfaVerifiedAt"`
Current bool `json:"current"`
}
SessionView is the client-facing representation of a session.
func ViewSession ¶
func ViewSession(s *store.Session, currentID string) SessionView
ViewSession converts a session to its client-facing view.
type SignInAttempt ¶
type SignInAttempt struct {
User *store.User
Method string
Provider string
Profile *oauth.Profile
IsNewUser bool
}
SignInAttempt describes a sign-in about to succeed.
type SignUpInput ¶
type SignUpInput struct {
Email string
Password string
Name string
// AnonymousUserID upgrades this guest user instead of creating a new
// one (set automatically by the HTTP handlers for guest sessions).
AnonymousUserID string
}
SignUpInput is the email + password sign-up request.
type SignUpResult ¶
type SignUpResult struct {
VerificationSent bool
Auth *AuthResult
}
SignUpResult is returned by SignUp. When email verification is required (the default) Session is nil and the response is identical whether or not the email was already registered.
type TOTPEnrollment ¶
type TOTPEnrollment struct {
Secret string `json:"secret"`
URL string `json:"otpauthUrl"`
QRCodePNG string `json:"qrCodePng"` // data: URL
}
TOTPEnrollment is returned when starting TOTP enrollment. Show the QR code (or secret) to the user and confirm with a code.
type Templates ¶
type Templates struct {
Email func(ctx context.Context, msg *notify.Email)
SMS func(ctx context.Context, msg *notify.SMS)
}
Templates rewrite outgoing messages. Each function may change Subject, Text (or anything else) in place; msg.Locale carries the request language.
type TokenConfig ¶
type TokenConfig struct {
VerifyEmailTTL time.Duration // default 24h
ResetTTL time.Duration // default 30m
MagicLinkTTL time.Duration // default 15m
OTPTTL time.Duration // default 10m
OTPLength int // default 6
MaxOTPAttempts int // default 5
}
TokenConfig controls one-time tokens and codes.
type URLs ¶
type URLs struct {
// SignIn is where browsers land after a redirect-based sign-in
// (OAuth, SAML, magic link) when no callbackUrl was given.
SignIn string
// Error receives ?error=<code> after a failed redirect-based flow.
Error string
// MFA is where browsers are sent when a redirect-based sign-in needs a
// second factor. The challenge is in an HttpOnly cookie.
MFA string
// VerifyEmail, if set, is used in verification emails (…?token=) and
// the page must POST the token to /auth/verify-email. Otherwise the
// email links to authgen's GET endpoint directly.
VerifyEmail string
// ResetPassword is the page that collects a new password (…?token=)
// and POSTs it to /auth/password/reset.
ResetPassword string
// MagicLink, if set, is used in magic-link emails (…?token=) and the
// page must POST the token to /auth/magic-link/verify. This protects
// links from being consumed by email security scanners.
MagicLink string
}
URLs are frontend URLs. All are optional.
type UserDetails ¶
type UserDetails struct {
User UserView `json:"user"`
Disabled bool `json:"disabled"`
MFAMethods []string `json:"mfaMethods"`
Sessions []SessionView `json:"sessions"`
Accounts []AccountView `json:"accounts"`
Passkeys []PasskeyView `json:"passkeys"`
APIKeys []APIKeyView `json:"apiKeys"`
}
UserDetails is an administrative view of a user.
type UserView ¶
type UserView struct {
ID string `json:"id"`
Email *string `json:"email"`
EmailVerified bool `json:"emailVerified"`
Phone *string `json:"phone"`
PhoneVerified bool `json:"phoneVerified"`
Name *string `json:"name"`
Image *string `json:"image"`
IsAnonymous bool `json:"isAnonymous"`
HasPassword bool `json:"hasPassword"`
CreatedAt time.Time `json:"createdAt"`
}
UserView is the client-facing representation of a user.
type WebAuthnConfig ¶
type WebAuthnConfig struct {
RPID string // e.g. "example.com"
RPDisplayName string // default AppName
RPOrigins []string // e.g. ["https://app.example.com"]
// CeremonyTTL bounds a registration/login ceremony. Default 5 minutes.
CeremonyTTL time.Duration
// RequireUserVerification makes the device always verify the user
// (fingerprint, face, iris or the device PIN) when registering a passkey
// and when it is used as a second factor or for reauthentication.
// Passwordless passkey sign-in always requires it.
RequireUserVerification bool
// PlatformOnly accepts only the device's built-in authenticator (Touch ID,
// Windows Hello, Android biometrics) at registration, not roaming
// security keys or another phone.
PlatformOnly bool
// Attestation is the attestation conveyance preference for
// registration: "none" (default, best privacy), "indirect", "direct"
// or "enterprise".
Attestation string
// AllowedAAGUIDs restricts registration to these authenticator models
// (AAGUIDs as UUID strings). AAGUIDs are self-reported unless
// attestation is verified, so combine this with Attestation "direct"
// and MDS for a real guarantee.
AllowedAAGUIDs []string
// MDS validates attestation against the FIDO Metadata Service
// (github.com/go-webauthn/webauthn/metadata).
MDS metadata.Provider
}
WebAuthnConfig configures WebAuthn (passkeys and security keys). Setting RPID enables WebAuthn as a second factor; Methods.Passkey additionally enables passwordless sign-in.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package biometric connects dedicated biometric scanners (fingerprint, iris, face readers at kiosks, attendance terminals or door controllers) to authgen without authgen ever handling biometric data.
|
Package biometric connects dedicated biometric scanners (fingerprint, iris, face readers at kiosks, attendance terminals or door controllers) to authgen without authgen ever handling biometric data. |
|
Package captcha verifies bot-protection tokens (Cloudflare Turnstile, hCaptcha, Google reCAPTCHA v3) before authgen performs abuse-prone actions (sign-up, sign-in, sending emails/SMS).
|
Package captcha verifies bot-protection tokens (Cloudflare Turnstile, hCaptcha, Google reCAPTCHA v3) before authgen performs abuse-prone actions (sign-up, sign-in, sending emails/SMS). |
|
cmd
|
|
|
authgen
command
Command authgen generates the database schema authgen needs, in the format of your migration tool.
|
Command authgen generates the database schema authgen needs, in the format of your migration tool. |
|
examples
|
|
|
server
command
Command server is a runnable example of authgen with PostgreSQL.
|
Command server is a runnable example of authgen with PostgreSQL. |
|
internal
|
|
|
secure
Package secure contains authgen's cryptographic primitives: random tokens, token hashing, constant-time comparison, Argon2id password hashing and a rotating keyring for authenticated encryption and MACs.
|
Package secure contains authgen's cryptographic primitives: random tokens, token hashing, constant-time comparison, Argon2id password hashing and a rotating keyring for authenticated encryption and MACs. |
|
Package notify defines how authgen delivers emails and SMS messages.
|
Package notify defines how authgen delivers emails and SMS messages. |
|
providers
|
|
|
oauth
Package oauth defines OAuth 2.0 / OpenID Connect provider configurations for authgen, plus presets for popular identity providers.
|
Package oauth defines OAuth 2.0 / OpenID Connect provider configurations for authgen, plus presets for popular identity providers. |
|
Package ratelimit provides the rate limiter used to throttle authentication attempts.
|
Package ratelimit provides the rate limiter used to throttle authentication attempts. |
|
Package schema describes the database tables authgen needs and lets the host application map them onto its own table and column names.
|
Package schema describes the database tables authgen needs and lets the host application map them onto its own table and column names. |
|
Package store defines the persistence interface authgen uses and the records it persists.
|
Package store defines the persistence interface authgen uses and the records it persists. |
|
memstore
Package memstore is an in-memory store.Store for tests and prototyping.
|
Package memstore is an in-memory store.Store for tests and prototyping. |
|
postgres
Package postgres implements store.Store on PostgreSQL using pgx/v5 and raw SQL.
|
Package postgres implements store.Store on PostgreSQL using pgx/v5 and raw SQL. |
|
storetest
Package storetest is a conformance suite for store.Store implementations.
|
Package storetest is a conformance suite for store.Store implementations. |
|
transport
|
|
|
admin
Package admin exposes authgen's administrative operations over HTTP: user search and inspection, disabling, deleting, signing users out, resetting MFA, SAML connection management and the audit log.
|
Package admin exposes authgen's administrative operations over HTTP: user search and inspection, disabling, deleting, signing users out, resetting MFA, SAML connection management and the audit log. |
|
graphql
Package graphql exposes authgen's JSON flows as a GraphQL endpoint.
|
Package graphql exposes authgen's JSON flows as a GraphQL endpoint. |
|
rest
Package rest exposes authgen as a JSON REST API (plus the browser redirect endpoints OAuth, SAML and email links require).
|
Package rest exposes authgen as a JSON REST API (plus the browser redirect endpoints OAuth, SAML and email links require). |