go-auth

Installation

Prerequisites, what you need before configuring go-auth, and a map of the configuration pattern.

Installation

Start with First working application for a runnable browser flow through signup, verification, 2FA, a protected request and logout. This page details prerequisites and integration choices.

Optional application roles require the fresh canonical schema and explicit initialization before signups. Use seed-admin --app-permissions to create the first protected administrator, then configure WithAppPermissions. Initialization does not install any library permissions. See the setup and permission guide.

Version 0.5.3 requires schema revision 3. Apply the matching migration catalog before starting the backend. Signup is closed by default: explicitly configure WithRegistration for public or invited account creation, and configure WithAuthentication separately for password/OAuth login.

Prerequisites

  • Go 1.26.10 or later
  • A database: PostgreSQL, MySQL, or SQLite
  • An SMTP server, or your own mailer implementation: required unless every email-sending feature is off (invites, email verification, 2FA, and admin login's two-factor challenge, the last of which is on by default and needs TwoFactorConfig.DisableAdminTwoFactor to turn off). EnvironmentDev is the one exception when a mailer is otherwise needed: with neither WithMailer nor WithEmail set, it falls back to a log-only driver. See Configuration.

Install

go get github.com/nazimdjebloun/go-auth

go-auth's go.mod requires pgx/v5 (PostgreSQL), modernc.org/sqlite (SQLite), and go-sql-driver/mysql (MySQL) directly; the last two are used by the goauth CLI, which registers all three drivers. The library imports the pgx stdlib driver itself, so PostgreSQL is registered automatically. For SQLite or MySQL, your program must still blank-import the driver package it uses so it registers with database/sql:

DatabasePackage
PostgreSQLgithub.com/jackc/pgx/v5/stdlib
SQLitemodernc.org/sqlite (pure Go, no CGO)
MySQLgithub.com/go-sql-driver/mysql

If the driver you configured is not actually registered (the import is missing), New() fails fast at startup with an error naming the missing import. It does not fail later on the first query.

The goauth CLI

The CLI shares the library's root module and release. Run it from the application's Go module without a version suffix to use the dependency selected by go.mod:

go run github.com/nazimdjebloun/go-auth/cmd/goauth migrate \
  --driver postgres --dsn "$DATABASE_URL"

From this source checkout, use go run ./cmd/goauth with the same arguments. For an installed binary, install an exact release matching the library and put $GOBIN or $GOPATH/bin on PATH. A go install/go run version suffix selects that release independently of the application's module. Avoid @latest for migration deployment: it can run a different schema catalog from your binary.

CommandWhat it does
migrateInstalls a published baseline or applies pending numbered auth migrations with a separate database journal. Requires --driver and --dsn.
migrate statusReports recorded history and pending IDs as JSON without DDL.
migrate verifyVerifies the tracked target schema and data postconditions.
migrate adopt --baseline 1Validates the supported untracked schema and records adoption without creation SQL.
migrate repair --id NVerifies the specified incomplete step before recording completion; executes no migration SQL.
generateExports auth.schema.sql, reference.md, and published migrations. Requires --driver; --out is a directory, default goauth.
seed-adminCreates the first administrator. See Admin → Creating the first admin.

Each command takes --help. Migrations covers deployment, adoption, recovery and the Go API. Keep auth migration ownership separate from the application's migration tool.

What you'll need before configuring

Gather these before writing your configuration:

  • A base URL for your frontend: used to build links in emails (verification, invites, password reset).
  • A database connection: either a connection string, or a database/pool you already opened yourself.
  • A signing secret: at least 32 random bytes. This is the one piece of key material the library needs; source it from your environment, never commit it.
  • The origins your frontend is served from: used for CSRF origin checking. No wildcard option exists.
  • A mailer, conditionally: required if you enable invite-only signup, email verification, or 2FA, or leave admin login's two-factor challenge on (the default; turn it off with TwoFactorConfig.DisableAdminTwoFactor for a mailer-free, API-only deployment). Either SMTP credentials or your own delivery implementation (Resend, Postmark, SES, etc.) work. EnvironmentDev alone falls back to a log-only driver when a mailer is needed but neither is configured.
  • OAuth credentials, conditionally: a client ID, client secret, and redirect URL per provider, only if you want OAuth login.

Nothing here is read from the environment by the library itself. go-auth has no notion of env vars. You decide how your program sources these values (environment variables are the usual choice) and pass them in as plain Go values.

The configuration pattern, at a glance

Pass option functions to NewConfig(opts ...Option). The table maps each option to its responsibility; Configuration documents every field and validation rule.

OptionConfigures
WithAppApp name, base URL, database connection, deployment environment
WithSecretThe root secret for CSRF, OAuth, 2FA, and OTP keys
WithSecurityPassword policy, optional email changes, email-link policy, pepper rotation timestamp
WithSessionSession, refresh-token, and verification/reset-token lifetimes
WithTwoFactorEmail two-factor settings
WithBrowserPublic API origin, exact allowed frontend origins, cookies and transport
WithAuthenticationAllowed password/OAuth login and credential methods for all accounts
WithRegistrationExplicit signup methods and global email-verification policy; signup is closed by default
WithOrganizationsMulti-tenant organizations
WithAppPermissionsOpt-in application roles and delegated library permissions
WithMaintenanceBackground cleanup of expired sessions and tokens
WithMailerA custom mailer implementation
WithEmailThe built-in SMTP mailer
WithTemplatesCustom email templates
WithPasswordHashingPassword algorithm (including Argon2id), bcrypt cost, optional versioned pepper keys, concurrency and shared work limiter
WithRateLimit and its narrower variantsPer-route rate limiting
WithProviderRegister an OAuth provider
WithLoggerStructured logging
WithAudit / WithAuditSinkAudit logging

Database setup

New requires a reachable database with the matching completed auth migration history. It checks both before starting workers, including with a borrowed database or pool. Run migrations separately; construction does not create or upgrade tables. SMTP configuration is validated, but startup does not promise delivery to a remote mailbox.

The published catalog and desired schema are embedded in the library. Apply pending auth migrations explicitly before starting the app:

go run github.com/nazimdjebloun/go-auth/cmd/goauth migrate \
  --driver postgres --dsn "$DATABASE_URL"

The initial catalog is revision 000001. Existing databases must match its complete schema before explicit adoption; old or partial schemas require reviewed reconciliation. Migrations defines these paths, and Schemas documents the auth objects.

Next

Redis (optional)

Redis uses github.com/redis/go-redis/v9 through the root module. Apply the current SQL migrations before enabling WithRedis. The complete feature requires Redis scripting and snapshot/TTL permissions; see Redis setup.

On this page