Complete example
A minimal foundation, then opt-in hardening and feature examples.
Read Quickstart first. This page shows the same foundation in one file, then the optional settings and Go API calls you can add when you need them.
1. The foundation
Copy this into main.go after go mod init and go get github.com/shakibdshy/signet-auth plus
modernc.org/sqlite. Run go mod tidy && go run ..
package main
import (
"context"
"crypto/rand"
"database/sql"
"log"
"net/http"
"os"
"sync"
"github.com/shakibdshy/signet-auth"
"github.com/shakibdshy/signet-auth/mailer/console"
"github.com/shakibdshy/signet-auth/store/sqlite"
_ "modernc.org/sqlite"
)
type memoryLimiter struct {
mu sync.Mutex
hits map[string]int
}
func (l *memoryLimiter) Allow(_ context.Context, key string) (bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
l.hits[key]++
return l.hits[key] <= 10, nil
}
func main() {
ctx := context.Background()
db, err := sql.Open("sqlite", "file:signet.db?_pragma=foreign_keys(1)")
if err != nil {
log.Fatal(err)
}
defer db.Close()
store := sqlite.New(db)
if err := store.Migrate(ctx); err != nil {
log.Fatal(err)
}
csrfKey := make([]byte, 32)
if _, err := rand.Read(csrfKey); err != nil {
log.Fatal(err)
}
cfg := signet.DefaultConfig()
cfg.Store = store
cfg.Mailer = console.New(os.Stdout) // development only
cfg.RateLimiter = &memoryLimiter{hits: make(map[string]int)}
cfg.CSRFKey = csrfKey
cfg.AppURL = "http://localhost:8080"
cfg.PathPrefix = "/auth"
// Development only. Remove both lines in production.
off := false
cfg.RequireVerifiedEmail = &off
cfg.SendVerificationOnSignUp = &off
auth, err := signet.New(cfg)
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
// The handler expects the full /auth/... path; do NOT use StripPrefix.
mux.Handle("/auth/", auth.Handler())
mux.Handle("/private", auth.RequireAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := signet.UserFromContext(r.Context())
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
_, _ = w.Write([]byte("hello " + user.Email + "\n"))
})))
log.Println("listening on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}DefaultConfig() sets secure cookie and session defaults. You supply the Store, Mailer,
RateLimiter and CSRFKey. signet.New validates the config and constructs the services;
auth.Handler() exposes every HTTP endpoint under PathPrefix.
2. Optional hardening
Add these before signet.New(cfg) only when you need them. Each setting is off by default. The
snippets use time, net/netip and your own cache/key values, so add those imports when you copy
them into the foundation program.
// Require recent authentication for sensitive routes.
cfg.Session.FreshAge = 5 * time.Minute
// Per-endpoint rules use published endpoint names.
cfg.RateLimitRules = map[string]signet.RateLimitRule{
"signin": {Limiter: &memoryLimiter{hits: make(map[string]int)}, KeyPrefix: "login"},
}
// Trust localhost proxies only. Without this, X-Forwarded-For is ignored.
cfg.TrustedProxies = []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}
// Opt-in session cache: bounded staleness, Store remains authoritative.
cfg.SessionCache = myCache // implements Get, Put and Flush
cfg.Session.CacheTTL = 30 * time.Second
// Opt-in key rings for rotation; existing single-key fields still work.
cfg.CSRFKeys = [][]byte{newKey, oldKey}
cfg.JWT = &signet.JWTConfig{
Algorithm: "RS256",
Keys: []any{newRSAKey, oldRSAKey},
Issuer: "signet",
}
// Mount auth.JWKSHandler() yourself if clients need key discovery.
// Opt-in redirect patterns for OAuth and passwordless callbacks.
cfg.AllowedRedirectPatterns = []string{"https://*.example.com"}See Sessions, JWT mode, Security and Passwordless sign-in for the semantics and trade-offs.
3. Calling features from your Go code
These methods call the same services as the HTTP endpoints. Use them inside your own handlers or jobs; they do not make HTTP requests and do not need CSRF tokens.
// Email/password
signUp, err := auth.SignUp(ctx, signet.SignUpInput{
Email: "ada@example.com", Password: "correct horse", Username: "ada",
})
result, err := auth.SignIn(ctx, signet.SignInInput{Email: "ada@example.com", Password: "correct horse"})
// Email change and account deletion: the raw proof comes from the emailed link.
err = auth.RequestEmailChange(ctx, signet.ChangeEmailInput{
UserID: signUp.User.ID, NewEmail: "new@example.com", CurrentPassword: "correct horse",
})
err = auth.VerifyEmailChange(ctx, signet.VerifyEmailChangeInput{Token: rawEmailToken})
err = auth.RequestUserDeletion(ctx, signet.RequestDeleteUserInput{UserID: signUp.User.ID})
err = auth.DeleteUser(ctx, signet.ConfirmDeleteUserInput{Token: rawDeleteToken})
// Passwordless
err = auth.SendMagicLink(ctx, signet.SendMagicLinkInput{Email: "ada@example.com"})
sent, err := auth.VerifyMagicLink(ctx, signet.VerifyMagicLinkInput{Token: rawLinkToken})
err = auth.SendEmailOTP(ctx, signet.SendEmailOTPInput{Email: "grace@example.com"})
otpResult, err := auth.VerifyEmailOTP(ctx, signet.VerifyEmailOTPInput{
Email: "grace@example.com", Code: "123456",
})
// Account management and Second factor
accounts, err := auth.ListAccounts(ctx, signet.ListAccountsInput{UserID: signUp.User.ID})
err = auth.UnlinkAccount(ctx, signet.UnlinkAccountInput{
UserID: signUp.User.ID, AccountID: accountID, SessionToken: result.SessionToken,
})
enabled, err := auth.EnableTwoFactor(ctx, signet.EnableTwoFactorInput{
UserID: signUp.User.ID, Password: "correct horse",
})
verified, err := auth.VerifyTwoFactor(ctx, signet.VerifyTwoFactorInput{
Challenge: enabled.Challenge, Code: "123456",
})The Go API returns SignInResult with User and SessionToken. When a User has Second factor
enabled, SignIn returns a TwoFactorChallenge instead; exchange it with VerifyTwoFactor.
HTTP endpoints
| Endpoint | Purpose |
|---|---|
POST /auth/signup, POST /auth/signin, POST /auth/signout | Email/password flows. |
GET /auth/csrf-token | Issue another CSRF token. |
GET /auth/accounts, POST /auth/unlink-account | Account management. |
POST /auth/send-magic-link, GET /auth/verify-magic-link | Magic link. |
POST /auth/send-otp, POST /auth/verify-otp | Email OTP. |
POST /auth/enable-two-factor, POST /auth/verify-two-factor, POST /auth/disable-two-factor, POST /auth/regenerate-backup-codes | Second factor. |
POST /auth/change-password, POST /auth/change-email, POST /auth/verify-change-email | Credential and email changes. |
POST /auth/request-account-deletion, POST /auth/confirm-account-deletion | Verified deletion. |
Authenticated endpoints derive the User ID from the session cookie — do not send user_id in
request bodies.