Skip to content

Latest commit

 

History

History
210 lines (181 loc) · 23.9 KB

README.md

File metadata and controls

210 lines (181 loc) · 23.9 KB

auth guides

Everything about using and extending github.com/ubgo/auth, an authentication library you import into a Go app. Start at the top if you are new; jump to a plugin or an integration if you know what you need.

Every Go snippet in these guides is copied by docsync from a program in examples/ that the test suite compiles and runs, and every HTTP transcript comes from a real run, so what you read is what the code does today.

ubgo/auth architecture: callers, transports, the operation pipeline, core and storage, with plugins beside them

Learning path

Read in this order to go from nothing to a production setup. Each step is one guide and one runnable example; stop at any step once your app has what it needs.

# Step What you learn Guide Example
1 Install The modules to go get, a database driver, a working auth.New Install quickstart
2 Your first app Sign-up, email verification, sign-in, a protected page and sign-out on net/http Your first app quickstart
3 How it fits together Plugins, the one operation pipeline, and calling every feature from Go as well as HTTP Plugins and the pipeline saas-workspace
4 Pick the ways in Password, magic link, mailed codes, passkeys, OAuth, phone, SSO: which ones fit your users Choose sign-in methods magic-link, passkeys, oauth
5 Connect your stack net/http, chi, gin, echo, fiber or GraphQL; a single-page app or a native client Choose a transport chi, gin, spa-cross-origin
6 Call it from the frontend The typed TypeScript client, cookie or bearer, the React hooks and components; its own 13-step path from a first call to production Client learning path, Choose a client setup ts-client-flows, react-headless, react-demo
7 Hold the session Cookie or bearer, database or Redis or stateless, caches, lifetimes, sign-out everywhere Sessions, Choose a session strategy session-strategies, mobile-bearer
8 Your data next to the library's The tables, reading and joining them, one transaction for your rows and the library's Databases, Transactions admin-plan, saas-workspace
9 Errors your users can read The error shape, matching errors in Go, translations, an error page for browser links Errors translated-errors
10 Harden the account A second factor, recent sign-in for sensitive actions, account settings and deletion Two-factor, Sessions › Step 8 two-factor, account-settings
11 Teams and permissions Organizations, invitations, roles, and your own permission model behind one interface Organizations, Authorization org-teams, authorizer
12 How an OIDC login works The six steps of one sign-in between an app, the login server and Google: state, PKCE, nonce, ID token checks guide sso-client
13 Test it End-to-end tests with SQLite in memory, recorded mail and a movable clock Test your app app-tests
14 Go to production Secrets, migrations from the deploy, the sweep, several instances, a reverse proxy, logs, metrics and traces, the checklist Going to production, net/http › Step 8 cli, multi-instance, behind-proxy, observability
15 Make it yours Plugins of your own: operations, hooks, columns, tables, identifier kinds Extending custom-plugin, plugin-tables

Start from your goal

I want to… Read Run
Add email and password sign-in to a Go app Your first app quickstart
Sign in without a password Magic links, mailed codes, email challenge magic-link, email-codes, email-challenge
Offer "Continue with Google / GitHub" OAuth oauth, oauth-providers
Use passkeys, or passkeys only Passkeys passkeys, passkey-first
Add two-factor authentication Two-factor two-factor, two-factor-options
Offer security keys as a second factor, or make a second factor mandatory Two-factor › Several factors two-factor-security-key
Serve a React, Vue or Svelte app on another origin SPA frontends spa-cross-origin
Drop in sign-in, sign-up, two-factor and account pages in a React app React UI kit react-demo (task demo)
Call the routes from TypeScript with types, including my own plugins TypeScript client, your own plugins ts-client-custom
Use the React auth screens on another API or identity SDK Put the React UI on another API examples/custom-backend
Build React auth screens in my own design system, with hooks only React hooks react-headless
Sign a CLI or Node script in from TypeScript and keep it signed in Bearer mode and other runtimes ts-client-bearer
Run verification, reset, magic link and second factor from TypeScript Client flows ts-client-flows
Choose between the prebuilt and a generated client, cookie and bearer, components and hooks Choose a client setup
Back a mobile app Mobile apps mobile-bearer, oauth-native
Sign in a CLI, TV or desktop app Device codes, desktop apps device-login, desktop-sign-in
Get pages without writing any auth UI Ready-made pages ready-made-pages, custom-pages
Build a SaaS with organizations and teams Organizations organizations, org-teams
Let people at a verified company domain join its organization Organizations › Step 16 org-domains
Use my own permission model (policies, relationships, attributes) Authorization authorizer
Sell to enterprises: SSO and SCIM SSO, SCIM sso-domains, scim
Give scripts API keys API keys api-key-lifecycle
Let other services verify my users JWT, other services jwt-keys, auth-server
Hand my users tokens Supabase, Hasura, Convex or Firebase accept JWT › Step 14 jwt-templates
Tell other services when users sign up, sign in or change Webhooks webhooks
Run one company login for my own internal apps, with a list of who may use each app SSO login server sso-server
Understand or write the app side of the SSO login server How an OIDC login works sso-client
Sign people in to my Go app through a login server, keep them signed in for days, and drop removed users within a minute OIDC client oidc-app
Be an OAuth / OpenID Connect provider or guard an MCP server OAuth provider oauth-provider
Let SAML services (wikis, ticketing, vendor tools) sign in with your app SAML identity provider saml-idp
Let agents act for my users Agent auth agent-auth
Gate an internal tool with no user database Login gate login-gate
Make sign-up invite-only Invite invite-only
Move users in from Auth0, Clerk, Supabase, Auth.js or WorkOS Migrating import-users
Block sign-ins by country, or catch impossible travel Geo rules geo-rules
Refuse a suspicious address, a script or a repeat trial sign-up Risk signals risk-signals
Send security events to my log drain or SIEM Security events security-events
Challenge suspicious traffic with proof of work instead of a captcha pow pow-challenge
Clean up accounts nobody uses stale stale-accounts
Run several instances behind a load balancer Going to production, Redis multi-instance, behind-proxy
Use ent for my own tables beside the library's ent ent-alongside
Pick the plugins for my kind of app Choose by kind of app

Choosing

Decision guides for the questions to settle before writing code: transport, sign-in methods, session strategy, database and storage, options by kind of app and the frontend client setup.

Getting started

Guide What you get
Install The modules to go get, a database, and a working auth.New
Your first app From an empty folder to sign-up, email verification, sign-in, a protected page and sign-out
Going to production Keys and secrets, configuration from the environment, migrations in deploys, scheduled cleanup, cookies and HTTPS, several instances, a security checklist
Test your app End-to-end tests of your own app with authtest: SQLite in memory, recorded mail and texts, a movable clock, sessions as cookies or contexts

Concepts

Page Explains
Plugins and the pipeline How plugins compose, and the one pipeline every Go call, HTTP route and GraphQL field runs through
Sessions Session tokens, lifetimes, stores, caches, stateless sessions, sign-out
Session tasks A step a signed-in session must finish (choose a workspace, enrol a second factor) before the rest of the app answers
Identifiers and verification Email, phone and username in one table, uniqueness, why only verified identities count
Errors Every error code, its HTTP status, and when it happens
Rate limits What is limited, per IP and per account, and where the counts live
Security events The stream of refusals and alerts (rate limits, credential stuffing, lockouts, geo) handed to your own sinks
Risk signals Your own IP reputation, bot and trial-abuse checks, with block, log or challenge and an explicit fail-open or fail-closed choice
Geo rules Country allow and deny rules and impossible-travel detection at sign-in, over a GeoIP source you supply
Security What the library guarantees, and what your app must still do
Transactions Writing your rows and the library's in one transaction
Configuration Every auth.With… option and environment variable
Databases Postgres, MySQL and SQLite, drivers, and reading the auth tables from your own queries
Migrations and maintenance Creating and upgrading tables, the CLI, and cleaning up expired rows
Multi-tenancy One deployment serving several tenants
How an OIDC login works One sign-in through the SSO login server, step by step: state, PKCE, nonce, the code, the ID token checks and signing out, with the real requests

Plugins

Plugin Guide
Email addresses, verification, change with undo, sign-in codes email
Passwords, reset, change, breached-password check password
Phone numbers and SMS codes phone
Usernames username
Sign in with an LDAP directory's username and password (OpenLDAP, Active Directory, FreeIPA) ldap
Sign in with an Ethereum wallet (ERC-4361) siwe
Magic links magiclink
Passwordless sign-in approved from the mail, the session landing in the browser that asked emailchallenge
Google, GitHub and any OpenID Connect issuer oauth
Passkeys passkey
Two-factor: authenticator app, mailed or texted codes, security keys, several per user, required enrolment twofactor
API keys apikey
Short-lived JWTs for other services, and templates shaped for Supabase, Hasura, Convex or Firebase jwt
Organizations, teams, invitations, roles and permissions, verified email domains organization
Permission statements and roles, for organizations or your own checks access
Admin: find, create, ban, set password, impersonate admin
Audit log of security events audit
Terms acceptance terms
Invite-only sign-up, with the invite's role invite
Referral codes and rewards referral
Guest sessions linked to the account they sign up with anonymous
Hand a session to a native app or another client handoff
Remember how each user last signed in lastlogin
Per-session app data in a table of its own sessiondata
Public, private and user-editable metadata per user metadata
Captcha before sign-up, sign-in and reset captcha
Proof-of-work challenge when a rate or geo rule asks for one, with no third party pow
Warn the owners of dormant accounts, and delete the ones that never answer stale
Signed outgoing webhooks (Standard Webhooks) on sign-up, sign-in, profile, identity and security events, with retries, dead letters and replay webhook
Sign a CLI or TV in with a device code (RFC 8628) deviceauth
Let other apps sign in with your app: OAuth 2.1 / OpenID Connect provider, MCP servers, per-client access oauthprovider
Let SAML 2.0 service providers sign in with your app: be the identity provider samlidp
Provision users and groups from Okta, Entra ID and other IdPs (SCIM 2.0) scim
Provider sign-in on preview deployments through production's callback oauthproxy
Provider sign-in in a popup for apps embedded on other sites oauthpopup
Enterprise single sign-on with OIDC and SAML identity providers sso
AI agents acting for a user under granted capabilities agentauth

Each plugin's folder in plugin/ also has a reference README with every option, route, table and error.

Frontend client

A typed TypeScript client generated from the same operations the Go server serves, for browsers, mobile apps, CLIs and servers, and a React kit on top of it: @ubgo/auth-react (provider and hooks) and shadcn components you copy in. docs/client has its own learning path from a first call to production and a table by goal; Choose a client setup settles the prebuilt or generated client, cookie or bearer, and components or hooks first.

The client's path from a click in React to a row in the database: registry components and your code, the provider and hooks, the generated client, cookie or bearer mode, the Go handler and pipeline, the tables; beside it, the generator that writes the client when Go changes

Guide What you get Example
Quickstart A browser app on the same site signs up, signs in, reads the session and signs out spa.ts
Plugins, Errors, Flows Plugin gating, typed error codes, and every mailed and multi-step flow ts-client-flows
Bearer mode and other runtimes Token stores, another site, mobile, CLIs, server-side code ts-client-bearer
Your own plugins Your app generates its own client for its own operations and error codes ts-client-custom
React UI kit, components, hooks, routers Ready-made screens, or hooks with your own markup, on any router react-demo, react-headless, react-router-app, nextjs-app
Reference, method reference Every option by example, every export, every method options.ts

Integrations

Where Guide
net/http, chi, gorilla net/http
gin gin
echo echo
fiber fiber
GraphQL with gqlgen GraphQL
Server-rendered pages with no UI to write ready-made pages
iOS and Android apps mobile apps
Desktop apps, Electron shells and CLIs signing in through the browser desktop apps
React, Vue, Svelte and other single-page apps SPA frontends; for React, the React UI kit
A typed TypeScript client for every route, with plugins toggled per client, generated by your own app for your own plugins TypeScript client: how it works, quickstart, plugins, your own plugins, bearer mode, errors, flows, reference
Redis and several app instances Redis
ent for your own tables beside the library's ent
Phone numbers typed the local way phone numbers
myapp auth migrate, auth sweep, auth maintain and the commands plugins add (auth oauth-client) CLI
Other services that verify your users other services
A login gate with no database: internal tools, prototypes, serverless login gate
One company login (an SSO / OpenID Connect server) for your own apps, with per-app access and provider-only sign-in pages SSO login server
A Go app (or a TypeScript server) that signs people in through such a login server, keeps them signed in for days and re-checks every minute OIDC client

Migrating from another system

Migrating: one guide per source, each on the same tested import program: Auth0, Clerk, Supabase, Auth.js / NextAuth and WorkOS, with the export command, the field map, what happens to passwords and the cutover checklist.

Extending

Extending auth: eleven guides on writing plugins of your own, from plugin anatomy to tables, hooks, identifier kinds, session rules, custom session stores, testing and shipping, and on bringing your own authorization.

Reference

  • Feature index: every feature by area, with its package, the guide section that explains it and the example that runs it.
  • HTTP API: every route, generated from the code; openapi.json is the same list as an OpenAPI 3.1 document with request and response schemas, and authhttp.OpenAPI serves an app's own.
  • TypeScript client methods: every method of the prebuilt client with its route, requirement and input and output types, generated from the code.
  • Error codes: every code with its status and message, generated from the declarations; error-codes.ts and error-codes.json are the same list for a TypeScript frontend and for tooling.
  • Troubleshooting: common mistakes and how to fix them.
  • Examples: a runnable program for every common setup.
  • Go reference on pkg.go.dev.