Quickstart for Go.

Add passkey and email and password sign-in to a Go web app with one call, then check it in four steps.

On this page
  1. Protect your routes

This is the library’s tested recipe: CI compiles it on every change, and examples/quickstart runs the same code with PasskeyOnly: true. A coding agent follows the same steps from /llms.txt.

  1. Add the module:

    Shell
    go get tensile.tools/auth@latest
  2. Build the server. This is the whole Go side; change only the origin, the RP name, and where your own routes go:

    Go
    import (
    	"context"
    	"crypto/rand"
    	"encoding/hex"
    	"errors"
    	"log/slog"
    	"os"
    
    	auth "tensile.tools/auth"
    	"tensile.tools/auth/authhttp"
    	"tensile.tools/auth/authroutes"
    	"tensile.tools/auth/memstore"
    	"tensile.tools/auth/passkey"
    	"tensile.tools/auth/password"
    	"tensile.tools/auth/ratelimit"
    )
    
    // The exact origin the browser uses. Use localhost, not 127.0.0.1:
    // a passkey's RPID must be a domain, and passkey.New refuses an IP.
    const origin = "http://localhost:8080"
    
    // newServer builds the server. ctx must live as long as the server:
    // svc.Run seals the audit log until it ends.
    func newServer(ctx context.Context) (http.Handler, error) {
    	store := memstore.New() // pgstore.New(db) in production, after pgstore.Migrate(ctx, db)
    	limiter, err := ratelimit.New(ratelimit.NewMemory(), ratelimit.DefaultRules())
    	if err != nil {
    		return nil, err
    	}
    	// The logger also gets every 500 that authhttp writes.
    	// 32 random bytes kept for the life of the audit log, for example
    	// from `openssl rand -hex 32`. The password package needs it. Keep it
    	// in your secret store, outside the repository; a new key breaks
    	// the link between old and new audit events for every address.
    	auditKey, err := hex.DecodeString(os.Getenv("AUTH_AUDIT_KEY"))
    	if err != nil {
    		return nil, err
    	}
    	svc, err := auth.New(store, auth.WithLimiter(limiter), auth.WithAuditKey(auditKey), auth.WithLogger(slog.Default()))
    	if err != nil {
    		return nil, err
    	}
    	go svc.Run(ctx) // seals the audit log and writes failure summaries once a minute
    	pk, err := passkey.New(svc, store, passkey.Config{RPID: "localhost", RPName: "My app", Origins: []string{origin}})
    	if err != nil {
    		return nil, err
    	}
    	pw, err := password.New(svc, store, password.Config{
    		Mailer: password.MailerFunc(sendMail),
    		// Called on email sign-up, with the confirmed address.
    		// Passkey sign-up calls authroutes.Config.NewUser instead.
    		NewUser: func(context.Context, password.NewUser) (auth.UserID, error) {
    			// Create the row in your users table and store this ID in it:
    			// every session names the user by it.
    			return auth.UserID("usr_" + rand.Text()), nil
    		},
    	})
    	if err != nil {
    		return nil, err
    	}
    	mux := authhttp.NewMux(svc, authhttp.WithClientIP(), authhttp.WithOrigins(origin))
    	authroutes.Mount(mux, authroutes.Config{Passkeys: pk, Passwords: pw})
    	// Your routes: every one declares authhttp.Public or authhttp.Need(...).
    	mux.HandleFunc("GET /{$}", authhttp.Public, servePage)
    	if err := mux.Check(); err != nil {
    		return nil, err // the message names each problem and its fix
    	}
    	return mux, nil
    }
    
    // sendMail queues m with your email provider and returns at once. Show
    // m.Code.Reveal(), the typed code, in large type, with m.CodePurpose()
    // and password.NeverShare beside it, say how long it works with
    // m.ValidFor(), and add the link m.Link.Reveal() (set
    // password.Config.Links). Never log either. A notice, such as
    // MessageAccountExists when someone signs up with a taken address,
    // has no code, and CodePurpose() is empty: write a short message for
    // each m.Kind instead.
    func sendMail(ctx context.Context, m password.Message) error {
    	return errors.New("sendMail: connect your email provider")
    }

    Email and password sign-in is on unless you set authroutes.Config{PasskeyOnly: true} instead of Passwords; Mount panics unless exactly one is set. RPID is the host name without a port: localhost locally, app.example.com in production. origin includes the scheme and port.

    There are two sign-up hooks, one for each way to sign up. password.Config.NewUser runs when someone confirms an email sign-up, and gets the address. authroutes.Config.NewUser runs when someone signs up with a passkey, and gets only the name they typed; its default makes a random ID. If your users table needs an email address, set methods: 'password' on the elements in step 3, so nobody signs up with a passkey alone. People can add a passkey after they sign in.

    The typed code in a sign-up or reset email works only in the browser that started the flow, which holds a binding cookie. To test sign-up with curl, keep cookies between requests with -c and -b, or use the link code, which works anywhere.

    Keep go svc.Run(ctx): until it seals an audit event, a change to that event is undetectable, and svc.VerifyAudit covers only sealed events. svc.UnsealedAudit counts the rest. auth.WithLogger also configures authhttp’s logging; pass authhttp.WithLogger to NewMux only to log authhttp somewhere else. An error from auth.New, passkey.New, password.New, or mux.Check is a setup error: its message names the field and the fix, so return or log it as it is, and never pass it to auth.Describe.

  3. Add the page. Use the elements instead of a hand-written page: the Go server serves them with the client, so there is no build step:

    HTML
    <tensile-sign-in redirect="/"></tensile-sign-in>
    <tensile-sign-up redirect="/"></tensile-sign-up>
    <script type="module">
      import { configure } from '/auth/client/elements/index.js'
      // With PasskeyOnly, add methods: 'passkey'. If your users table needs
      // an email address, add methods: 'password'.
      configure({ appName: 'Acme', theme: 'auto' })
    </script>

    For the account page and approvals, see Use the drop-in elements instead of hand-written pages.

    GET /auth/me answers the signed-in session as JSON, or 401.

  4. Verify, in this order:

    1. go vet ./... passes.
    2. Starting the server doesn’t fail in mux.Check().
    3. curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/auth/client/elements/index.js prints 200.
    4. curl -s -X POST http://localhost:8080/auth/passkey/sign-in/begin prints JSON with publicKey.

examples/quickstart is the same server with PasskeyOnly: true, as a running app.

Protect your routes

Declare what each route needs; the library enforces, records, and explains refusals:

Go
mux.HandleFunc("GET /repos/{id}", authhttp.Need(auth.Need{Human: true}), showRepo)
mux.HandleFunc("DELETE /repos/{id}", authhttp.Need(auth.Need{Assurance: auth.AssuranceMulti, Within: 10 * time.Minute, Human: true}), deleteRepo)

In a handler, p, _ := auth.FromContext(r.Context()) is the caller. Send every library error to the client with authhttp.Error(w, r, err). In the browser, use auth.fetch(path, init): it confirms with a passkey when a route needs a recent check, and retries once.

An agent’s p.User is the human it acts for. Scopes alone let an agent do anything its human can within them. Every route that uses the user’s identity for something only the person should do, such as accepting an invitation, creating an account-level resource, or listing everything the person has, must refuse agents: declare it with authhttp.Need(auth.Need{Human: true}), or check p.IsAgent() in the handler and answer authhttp.Error(w, r, svc.Require(r.Context(), p, auth.Need{Action: "invite.accept", Human: true})).