Documentation
¶
Overview ¶
Package nine is the official Go SDK for 9in (https://9in.io): hosted login, OpenID Connect provider and single sign-on.
It uses only the standard library and covers:
- Signing users in to web apps: WebApp mounts /nine/login, /nine/callback and /nine/logout with an encrypted cookie session and WebApp.RequireUser middleware; WebAppAuth is the flow underneath (authorization code + PKCE, state, nonce, the RFC 9207 iss check, ID token verification, refresh token rotation, logout).
- Protecting APIs: Verifier checks access tokens locally with every algorithm of 9in's key library, or in hybrid mode (local check plus one cached introspection per token, evicted by webhooks) so revocations apply at once. RequireAuth is the net/http middleware and ClaimsFrom reads the claims.
- The Management API: ManagementClient (users, sessions, login links, imports).
- Keeping users in your own database: AdapterHandler serves the adapter protocol v2.
- Webhooks: VerifyWebhook and WebhookHandler, which processes each event once (EventStore, MemoryEventStore).
- CLIs, devices and services: DeviceAuth (RFC 8628) and ClientCredentials.
Every type is safe for concurrent use: create clients once and share them. Every call takes a context.Context; network calls have a 10-second timeout by default, never follow redirects, and nothing is logged. Every failure is an *Error with an OAuth-style Code and an HTTP Status; test for codes with errors.Is and the Err values.
Issuers must use https: http is accepted only for localhost, *.localhost and loopback addresses, unless you allow it (AllowInsecureIssuer, NINE_ALLOW_INSECURE_ISSUER=true).
Guides are at https://9in.io/docs/.
Example ¶
Sign users in to a web app: the routes, an encrypted cookie session and protected pages.
package main
import (
"fmt"
"log"
"net/http"
nine "github.com/9in-io/go-sdk"
)
func main() {
// NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_SECRET (32+ characters) and NINE_BASE_URL.
app, err := nine.NewWebApp(nine.WebAppConfigFromEnv())
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/nine/", app) // /nine/login, /nine/signup, /nine/callback, /nine/logout
mux.Handle("/dashboard", app.RequireUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := nine.UserFrom(r.Context())
fmt.Fprintf(w, "Hello %s", user.Name)
})))
log.Fatal(http.ListenAndServe(":3000", mux))
}
Output:
Index ¶
- Constants
- Variables
- func AdapterHandler(cfg AdapterConfig) http.Handler
- func CodeChallenge(verifier string) string
- func DefaultScopes() []string
- func Env(name string) string
- func NormalizeIssuer(issuer string, allowInsecure bool) (string, error)
- func RequireAuth(v AccessTokenVerifier, scopes ...string) func(http.Handler) http.Handler
- func SafeReturnPath(path string) string
- func SignPayload(secret, method, path string, body []byte) string
- func SignPayloadAt(secret, method, path string, body []byte, at time.Time) string
- func VerifySignature(secrets []string, header, method, path string, body []byte, ...) error
- func WebhookHandler(cfg WebhookConfig) http.Handler
- func WithClaims(ctx context.Context, claims Claims) context.Context
- func WriteAuthError(w http.ResponseWriter, err error, scopes ...string)
- type AccessTokenVerifier
- type Adapter
- type AdapterConfig
- type AdapterEvent
- type AdapterUser
- type AnswerCache
- type AuthMiddleware
- type CachedAnswer
- type Claims
- func (c Claims) Audience() []string
- func (c Claims) Bool(name string) bool
- func (c Claims) ClientID() string
- func (c Claims) ExpiresAt() time.Time
- func (c Claims) HasScope(scope string) bool
- func (c Claims) Int(name string) (int64, bool)
- func (c Claims) IsMachine() bool
- func (c Claims) Issuer() string
- func (c Claims) Scopes() []string
- func (c Claims) SessionID() string
- func (c Claims) String(name string) string
- func (c Claims) Strings(name string) []string
- func (c Claims) Subject() string
- func (c Claims) Time(name string) time.Time
- func (c Claims) TokenID() string
- type ClientCredentials
- type ClientCredentialsConfig
- type ClientCredentialsOptions
- type DeviceAuth
- func (d *DeviceAuth) EnsureFresh(ctx context.Context, tokens *TokenSet, leeway time.Duration) (*TokenSet, error)
- func (d *DeviceAuth) Poll(ctx context.Context, code *DeviceCode) (*TokenSet, error)
- func (d *DeviceAuth) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error)
- func (d *DeviceAuth) Revoke(ctx context.Context, token, hint string) error
- func (d *DeviceAuth) Start(ctx context.Context) (*DeviceCode, error)
- func (d *DeviceAuth) UserInfo(ctx context.Context, accessToken string) (Claims, error)
- func (d *DeviceAuth) Wait(ctx context.Context, code *DeviceCode) (*TokenSet, error)
- type DeviceAuthConfig
- type DeviceCode
- type Discovery
- type Error
- type EventDeduplicator
- type EventStore
- type Identifier
- type ImportIdentity
- type ImportOptions
- type ImportResult
- type ImportUser
- type ListUsersOptions
- type Login
- type LoginLink
- type LoginLinkOptions
- type LoginOptions
- type LogoutOptions
- type MFAState
- type ManagedIdentity
- type ManagedSession
- type ManagedUser
- type ManagementClient
- func (m *ManagementClient) BlockUser(ctx context.Context, id string) (*ManagedUser, error)
- func (m *ManagementClient) CreateLoginLink(ctx context.Context, id string, opts LoginLinkOptions) (*LoginLink, error)
- func (m *ManagementClient) CreateUser(ctx context.Context, user NewUser) (*ManagedUser, error)
- func (m *ManagementClient) DeleteUser(ctx context.Context, id string) error
- func (m *ManagementClient) FindUser(ctx context.Context, field, value string) (*ManagedUser, error)
- func (m *ManagementClient) FindUserByEmail(ctx context.Context, email string) (*ManagedUser, error)
- func (m *ManagementClient) GetUser(ctx context.Context, id string) (*UserDetail, error)
- func (m *ManagementClient) ImportUsers(ctx context.Context, users []ImportUser, opts ImportOptions) ([]ImportResult, error)
- func (m *ManagementClient) ListUserSessions(ctx context.Context, id string) ([]ManagedSession, error)
- func (m *ManagementClient) ListUsers(ctx context.Context, opts ListUsersOptions) (*UserList, error)
- func (m *ManagementClient) RevokeSession(ctx context.Context, sid string) error
- func (m *ManagementClient) RevokeUserSessions(ctx context.Context, id string) (int, error)
- func (m *ManagementClient) UnblockUser(ctx context.Context, id string) (*ManagedUser, error)
- func (m *ManagementClient) UpdateUser(ctx context.Context, id string, changes UserChanges) (*ManagedUser, error)
- type ManagementConfig
- type MemoryAnswerCache
- func (c *MemoryAnswerCache) Clear(context.Context)
- func (c *MemoryAnswerCache) Evict(_ context.Context, claim, value string) int
- func (c *MemoryAnswerCache) Get(_ context.Context, key string) (CachedAnswer, bool)
- func (c *MemoryAnswerCache) Len() int
- func (c *MemoryAnswerCache) Set(_ context.Context, key string, answer CachedAnswer)
- type MemoryEventStore
- func (s *MemoryEventStore) Add(_ context.Context, key, value string, ttl time.Duration) (bool, error)
- func (s *MemoryEventStore) Delete(_ context.Context, key string) error
- func (s *MemoryEventStore) Get(_ context.Context, key string) (string, bool, error)
- func (s *MemoryEventStore) Set(_ context.Context, key, value string, ttl time.Duration) error
- type Mode
- type NewUser
- type PendingLogin
- type ProcessStatus
- type TokenSet
- type User
- type UserChanges
- type UserDetail
- type UserList
- type UserQuery
- type Verifier
- func (v *Verifier) Clear(ctx context.Context)
- func (v *Verifier) HandleEvent(ctx context.Context, event *WebhookEvent) int
- func (v *Verifier) Issuer() string
- func (v *Verifier) Mode() Mode
- func (v *Verifier) Verify(ctx context.Context, token string, scopes ...string) (Claims, error)
- func (v *Verifier) VerifyIDToken(ctx context.Context, idToken, clientID, nonce string) (Claims, error)
- type VerifierConfig
- type WebApp
- func (a *WebApp) AccessToken(w http.ResponseWriter, r *http.Request) (string, error)
- func (a *WebApp) Auth() *WebAppAuth
- func (a *WebApp) Callback(w http.ResponseWriter, r *http.Request)
- func (a *WebApp) Login(w http.ResponseWriter, r *http.Request)
- func (a *WebApp) Logout(w http.ResponseWriter, r *http.Request)
- func (a *WebApp) Middleware(next http.Handler) http.Handler
- func (a *WebApp) RequireUser(next http.Handler) http.Handler
- func (a *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *WebApp) Signup(w http.ResponseWriter, r *http.Request)
- func (a *WebApp) User(r *http.Request) *User
- type WebAppAuth
- func (a *WebAppAuth) ClientCredentials(ctx context.Context, opts ClientCredentialsOptions) (*TokenSet, error)
- func (a *WebAppAuth) ClientID() string
- func (a *WebAppAuth) CreateLogin(ctx context.Context, opts LoginOptions) (*Login, error)
- func (a *WebAppAuth) Discovery(ctx context.Context) (*Discovery, error)
- func (a *WebAppAuth) EnsureFresh(ctx context.Context, tokens *TokenSet, leeway time.Duration) (*TokenSet, error)
- func (a *WebAppAuth) HandleCallback(ctx context.Context, query url.Values, pending *PendingLogin) (*TokenSet, error)
- func (a *WebAppAuth) Issuer() string
- func (a *WebAppAuth) LogoutURL(ctx context.Context, opts LogoutOptions) (string, error)
- func (a *WebAppAuth) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error)
- func (a *WebAppAuth) Revoke(ctx context.Context, token, hint string) error
- func (a *WebAppAuth) UserInfo(ctx context.Context, accessToken string) (Claims, error)
- func (a *WebAppAuth) VerifyIDToken(ctx context.Context, idToken, nonce string) (Claims, error)
- type WebAppAuthConfig
- type WebAppConfig
- type WebhookConfig
- type WebhookEvent
Examples ¶
Constants ¶
const ( // SignatureHeader carries t=<unix seconds>,v1=<hex HMAC-SHA256>. SignatureHeader = "9in-signature" // RequestIDHeader identifies an adapter request; responses are signed over it. RequestIDHeader = "9in-request-id" // EventIDHeader, EventTypeHeader and DeliveryIDHeader come with webhooks. EventIDHeader = "9in-event-id" EventTypeHeader = "9in-event-type" DeliveryIDHeader = "9in-delivery-id" )
Headers of 9in's signed requests (adapter protocol v2 and webhooks).
const DefaultTolerance = 5 * time.Minute
DefaultTolerance is how far a signature's timestamp may be from now.
const OpaquePrefix = "9in_at_"
OpaquePrefix starts 9in's opaque access tokens, which are always introspected.
const Version = "0.1.0"
Version is the version of this SDK, sent in the User-Agent header.
Variables ¶
var ( // ErrInvalidToken: an access token failed verification (401). ErrInvalidToken = &Error{Code: "invalid_token", Status: http.StatusUnauthorized} // ErrInsufficientScope: the token is valid but lacks a required scope (403). ErrInsufficientScope = &Error{Code: "insufficient_scope", Status: http.StatusForbidden} // ErrInvalidIDToken: an ID token failed verification. ErrInvalidIDToken = &Error{Code: "invalid_id_token", Status: http.StatusUnauthorized} // ErrInvalidState: a callback doesn't match a sign-in in progress (another browser, a // replay, or it took longer than 15 minutes). ErrInvalidState = &Error{Code: "invalid_state", Status: http.StatusBadRequest} // ErrInvalidIssuer: the callback's iss parameter isn't your issuer, or the issuer URL // is malformed. ErrInvalidIssuer = &Error{Code: "invalid_issuer", Status: http.StatusBadRequest} // ErrInsecureIssuer: the issuer isn't https (and isn't localhost or loopback). ErrInsecureIssuer = &Error{Code: "insecure_issuer"} // ErrLoginRequired: there is no session, or it ended. ErrLoginRequired = &Error{Code: "login_required", Status: http.StatusUnauthorized} // ErrInvalidGrant: 9in refused a code or refresh token (used, expired or revoked). ErrInvalidGrant = &Error{Code: "invalid_grant", Status: http.StatusBadRequest} // ErrAccessDenied: the user cancelled or declined. ErrAccessDenied = &Error{Code: "access_denied", Status: http.StatusBadRequest} // ErrInvalidSignature: a webhook or adapter request failed signature verification. ErrInvalidSignature = &Error{Code: "invalid_signature", Status: http.StatusUnauthorized} // ErrNotFound: the Management API found no such user or session (404; it also // matches the API's user_not_found). ErrNotFound = &Error{Code: "not_found", Status: http.StatusNotFound} // ErrInvalidOptions: a required setting is missing or invalid. ErrInvalidOptions = &Error{Code: "invalid_options"} // ErrAuthorizationPending: device flow, the user hasn't approved yet. ErrAuthorizationPending = &Error{Code: "authorization_pending", Status: http.StatusBadRequest} // ErrSlowDown: device flow, polling too fast. ErrSlowDown = &Error{Code: "slow_down", Status: http.StatusBadRequest} // ErrExpiredToken: device flow, the code expired before the user approved it. ErrExpiredToken = &Error{Code: "expired_token", Status: http.StatusBadRequest} // ErrInvalidCredentials is what an [Adapter]'s Authenticate returns for an unknown // user or a wrong password (9in doesn't tell them apart). ErrInvalidCredentials = &Error{Code: "invalid_credentials", Status: http.StatusUnauthorized} // ErrUserBlocked is what an [Adapter]'s Authenticate returns for a blocked user. ErrUserBlocked = &Error{Code: "blocked", Status: http.StatusForbidden} )
Errors to test for with errors.Is. They match any *Error with the same Code.
Functions ¶
func AdapterHandler ¶
func AdapterHandler(cfg AdapterConfig) http.Handler
AdapterHandler returns an http.Handler for the adapter protocol v2. Mount it at your adapter's base URL; it serves …/authenticate, …/user and …/event, answering with the same routes, bodies and status codes as the other 9in SDKs:
- authenticate: 200 {user}, 401 invalid_credentials, 403 blocked
- user: 200 {user}, 404 not_found
- event: 204
- 400 invalid_json or invalid_request for a malformed body, 404 for another route, 500 server_error when the adapter fails
Requests must carry a valid 9in-signature over the method, the path as sent and the raw body (unsigned answers: 401 invalid_signature, 405 for non-POST). Every other answer is signed over "<path>#<9in-request-id>", so it can't be replayed for another request.
Mount it on the path 9in calls (http.StripPrefix is fine: the signed path is read from the request line). It panics when Adapter or the secret is missing.
Example ¶
package main
import (
"context"
"net/http"
"os"
nine "github.com/9in-io/go-sdk"
)
// myUsers is your user database.
type myUsers struct{}
func (myUsers) Authenticate(ctx context.Context, id nine.Identifier, password string) (*nine.AdapterUser, error) {
if id.Value != "jane@acme.com" || password != "hunter2" {
return nil, nine.ErrInvalidCredentials
}
return &nine.AdapterUser{ID: "42", Email: "jane@acme.com", EmailVerified: true, Name: "Jane Doe"}, nil
}
func (myUsers) FindUser(ctx context.Context, q nine.UserQuery) (*nine.AdapterUser, error) {
if q.ID == "42" || (q.Identifier != nil && q.Identifier.Value == "jane@acme.com") {
return &nine.AdapterUser{ID: "42", Email: "jane@acme.com", Name: "Jane Doe"}, nil
}
return nil, nil
}
func (myUsers) OnEvent(ctx context.Context, e *nine.AdapterEvent) error {
if e.EventType == "otp.requested" {
return sendCode(ctx, e.Data["channel"], e.Data["to"], e.Data["code"])
}
return nil
}
func sendCode(ctx context.Context, channel, to, code any) error { return nil }
func main() {
// Serves /nine/authenticate, /nine/user and /nine/event.
http.Handle("/nine/", nine.AdapterHandler(nine.AdapterConfig{
Secret: os.Getenv("NINE_ADAPTER_SECRET"),
Adapter: myUsers{},
}))
}
Output:
func CodeChallenge ¶
CodeChallenge is the PKCE S256 challenge for a code verifier (RFC 7636): BASE64URL(SHA256(verifier)).
Example ¶
package main
import (
"fmt"
nine "github.com/9in-io/go-sdk"
)
func main() {
fmt.Println(nine.CodeChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"))
}
Output: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
func DefaultScopes ¶
func DefaultScopes() []string
DefaultScopes returns the scopes requested when a configuration names none: an ID token with the profile and email claims, and a refresh token.
func Env ¶
Env returns the value of the NINE_<name> environment variable, or "" when it is unset. Env("ISSUER") and Env("NINE_ISSUER") both read NINE_ISSUER.
The settings this package reads are NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI, NINE_AUDIENCE, NINE_API_SECRET (an API's HMAC secret), NINE_ADAPTER_SECRET, NINE_WEBHOOK_SECRET, NINE_SECRET and NINE_BASE_URL (WebApp), and NINE_ALLOW_INSECURE_ISSUER. Only the …FromEnv functions read them.
func NormalizeIssuer ¶
NormalizeIssuer checks an issuer URL and returns it without a trailing slash.
Issuers must use https, so a typo can't send tokens or credentials in clear text. Plain http is accepted for localhost, *.localhost and loopback addresses (development), when allowInsecure is true, or when NINE_ALLOW_INSECURE_ISSUER=true. An issuer with a query, a fragment or credentials is refused. The errors are invalid_issuer and insecure_issuer.
Every constructor in this package calls it, so you only need it to check a setting early.
Example ¶
package main
import (
"fmt"
nine "github.com/9in-io/go-sdk"
)
func main() {
issuer, err := nine.NormalizeIssuer("https://acme.9in.io/", false)
fmt.Println(issuer, err)
_, err = nine.NormalizeIssuer("http://acme.9in.io", false)
fmt.Println(err)
issuer, err = nine.NormalizeIssuer("http://localhost:8787", false)
fmt.Println(issuer, err)
}
Output: https://acme.9in.io <nil> nine: insecure_issuer: issuer must use https (got http://acme.9in.io); plain http is only accepted for localhost http://localhost:8787 <nil>
func RequireAuth ¶
RequireAuth is net/http middleware for your API: it verifies the "Authorization: Bearer …" access token with v, requires every scope given (each argument may hold several, space-separated), and puts the claims in the request context (ClaimsFrom).
A missing or bad token gets 401 invalid_token, a missing scope 403 insufficient_scope, both as JSON with a WWW-Authenticate header (RFC 6750). When verification itself fails (9in unreachable, introspection refused) the answer is 503: that is your server's problem, not the caller's. Use AuthMiddleware to change these answers or to let requests without a token through.
Example ¶
package main
import (
"fmt"
"log"
"net/http"
nine "github.com/9in-io/go-sdk"
)
func main() {
verifier, err := nine.NewVerifier(nine.VerifierConfigFromEnv()) // NINE_ISSUER, NINE_AUDIENCE…
if err != nil {
log.Fatal(err)
}
orders := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims := nine.ClaimsFrom(r.Context())
if claims.IsMachine() { // a client-credentials token: no user
http.Error(w, "users only", http.StatusForbidden)
return
}
fmt.Fprintf(w, "orders of %s", claims.Subject())
})
http.Handle("GET /api/orders", nine.RequireAuth(verifier, "orders:read")(orders))
}
Output:
func SafeReturnPath ¶
SafeReturnPath returns path when it is a path on your own site ("/dashboard?tab=1"), and "" for anything that could send the user elsewhere: absolute URLs, protocol-relative "//host" and "/\host", or control characters.
Example ¶
package main
import (
"fmt"
nine "github.com/9in-io/go-sdk"
)
func main() {
for _, p := range []string{"/dashboard?tab=2", "https://evil.example", "//evil.example", "/\\evil.example"} {
fmt.Printf("%q\n", nine.SafeReturnPath(p))
}
}
Output: "/dashboard?tab=2" "" "" ""
func SignPayload ¶
SignPayload signs a request or response the way 9in does, with the current time: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<METHOD>.<path>.<body>")>. It returns the 9in-signature header value. Adapter responses are signed over "<path>#<request id>".
func SignPayloadAt ¶
SignPayloadAt is SignPayload with a given time.
Example ¶
package main
import (
"fmt"
"time"
nine "github.com/9in-io/go-sdk"
)
func main() {
body := []byte(`{"identifier":{"type":"email","value":"jane@acme.com"},"password":"hunter2"}`)
header := nine.SignPayloadAt("adapter_secret_test", "POST", "/nine/authenticate", body, time.Unix(1762682400, 0))
fmt.Println(header)
}
Output: t=1762682400,v1=f8c341feb9ffa2698aa90a3e762f7108a324e503aa260bbc305e8ba3be9ca49c
func VerifySignature ¶
func VerifySignature(secrets []string, header, method, path string, body []byte, tolerance time.Duration) error
VerifySignature checks a 9in-signature header against a request's method, path and raw body, with any of secrets (several while you rotate) and a timestamp tolerance (0 means DefaultTolerance). It fails with invalid_signature (Status 401), whose Description is the reason: missing, malformed, expired or mismatch.
Example ¶
package main
import (
"fmt"
nine "github.com/9in-io/go-sdk"
)
func main() {
body := []byte(`{"id":"42"}`)
header := nine.SignPayload("new-secret", "POST", "/nine/user", body)
// Several secrets while you rotate; 0 means the default 5-minute tolerance.
err := nine.VerifySignature([]string{"new-secret", "old-secret"}, header, "POST", "/nine/user", body, 0)
fmt.Println(err)
err = nine.VerifySignature([]string{"other"}, header, "POST", "/nine/user", body, 0)
fmt.Println(err)
}
Output: <nil> nine: invalid_signature: mismatch
func WebhookHandler ¶
func WebhookHandler(cfg WebhookConfig) http.Handler
WebhookHandler returns an http.Handler for your webhook endpoint. It answers:
- 204 when the event was handled, or had already been (a retry or redelivery);
- 409 while another delivery of the same event is still being handled (9in retries);
- 401 for a bad signature, 400 for a body that isn't an event, 405 for non-POST;
- 500 when Handle failed (the event id is released, so 9in's retry handles it).
It panics when no secret is given (a configuration error, found at startup).
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"os"
nine "github.com/9in-io/go-sdk"
)
func main() {
http.Handle("POST /nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
Secret: os.Getenv("NINE_WEBHOOK_SECRET"),
// Called once per event; return an error to have 9in retry later.
Handle: func(ctx context.Context, e *nine.WebhookEvent) error {
switch e.EventType {
case "user.created":
user, err := e.User()
if err != nil {
return err
}
fmt.Println("welcome", user.Email)
case "user.deleted":
fmt.Println("goodbye", e.UserID())
}
return nil
},
// Store: a shared EventStore (Redis SET NX…) when you run several instances.
}))
}
Output:
func WithClaims ¶
WithClaims returns a copy of ctx carrying claims (what RequireAuth does; handy in tests).
func WriteAuthError ¶
func WriteAuthError(w http.ResponseWriter, err error, scopes ...string)
WriteAuthError writes the answer for a failed token check: 401 invalid_token, 403 insufficient_scope (naming the required scopes), or 503 for anything else, as JSON with a WWW-Authenticate header.
Types ¶
type AccessTokenVerifier ¶
type AccessTokenVerifier interface {
Verify(ctx context.Context, token string, scopes ...string) (Claims, error)
}
AccessTokenVerifier verifies bearer tokens. *Verifier implements it; so can a fake in your tests.
type Adapter ¶
type Adapter interface {
// Authenticate checks a password. Return the user, or ErrInvalidCredentials (or a nil
// user) for an unknown user or a wrong password, or ErrUserBlocked (or a user with
// Blocked set) for a blocked one. Any other error answers 500.
Authenticate(ctx context.Context, id Identifier, password string) (*AdapterUser, error)
// FindUser looks a user up by id or identifier. Return a nil user (or ErrNotFound)
// when there is none.
FindUser(ctx context.Context, query UserQuery) (*AdapterUser, error)
// OnEvent receives notifications, including otp.requested when you deliver one-time
// codes yourself.
OnEvent(ctx context.Context, event *AdapterEvent) error
}
Adapter is your user database, as 9in sees it (adapter protocol v2).
type AdapterConfig ¶
type AdapterConfig struct {
// Adapter is your user database (required).
Adapter Adapter
// Secret is the connection's shared secret (Connections → User database;
// NINE_ADAPTER_SECRET). Responses are signed with it.
Secret string
// Secrets are more secrets accepted while you rotate.
Secrets []string
// Tolerance is the signature timestamp tolerance. Default 5 minutes.
Tolerance time.Duration
// OnError is told about adapter errors that were answered with 500. Optional.
OnError func(r *http.Request, err error)
}
AdapterConfig configures AdapterHandler.
type AdapterEvent ¶
type AdapterEvent struct {
ID string `json:"id"`
EventType string `json:"event_type"`
CreatedAt time.Time `json:"created_at"`
Data map[string]any `json:"data"`
}
AdapterEvent is what 9in posts to …/event. Data["user_id"] is your own user id. otp.requested carries user_id, channel ("email" or "sms"), to, code, purpose ("login" or "password_reset") and expires_at; user.updated and user.password_changed carry user_id and fields.
func (*AdapterEvent) UserID ¶
func (e *AdapterEvent) UserID() string
UserID is data.user_id: your own user id, or "".
type AdapterUser ¶
type AdapterUser struct {
// ID is your user id (required, up to 256 characters).
ID string `json:"id"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
PhoneNumber string `json:"phone_number,omitempty"` // E.164
PhoneNumberVerified bool `json:"phone_number_verified,omitempty"`
Username string `json:"username,omitempty"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"` // https URL
Locale string `json:"locale,omitempty"`
Zoneinfo string `json:"zoneinfo,omitempty"`
Birthdate string `json:"birthdate,omitempty"` // YYYY-MM-DD
Blocked bool `json:"blocked,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
AdapterUser is a user from your database, in the shape 9in expects (OpenID Connect claim names). Empty fields are left out. Metadata is stored on the 9in user.
type AnswerCache ¶
type AnswerCache interface {
// Get returns the answer for key, if there is one.
Get(ctx context.Context, key string) (CachedAnswer, bool)
// Set stores an answer until answer.Until.
Set(ctx context.Context, key string, answer CachedAnswer)
// Evict removes every answer whose claims have claim (jti, sid or sub) equal to
// value, and returns how many it removed.
Evict(ctx context.Context, claim, value string) int
// Clear removes every answer.
Clear(ctx context.Context)
}
AnswerCache keeps hybrid verification answers, keyed by a SHA-256 hash of the token. The default is in memory, per process (NewMemoryAnswerCache). A shared implementation (Redis, your database) lets every process see an eviction made by the one that received the webhook; it must also find entries by claim for Evict. Methods are called concurrently and should not fail: treat a backend error as a miss.
type AuthMiddleware ¶
type AuthMiddleware struct {
// Verifier checks the tokens (required).
Verifier AccessTokenVerifier
// Scopes must all be granted.
Scopes []string
// Optional lets requests without a bearer token through, without claims. A bearer
// token that is present must still be valid.
Optional bool
// OnError writes the answer when verification fails. Default: 401, 403 or 503 JSON.
OnError func(w http.ResponseWriter, r *http.Request, err error)
}
AuthMiddleware is RequireAuth with more choices.
type CachedAnswer ¶
type CachedAnswer struct {
// Claims are the token's claims, or nil when 9in said it is not active.
Claims Claims `json:"claims"`
// Until is when the answer must be asked again.
Until time.Time `json:"until"`
}
CachedAnswer is what hybrid verification remembers about a token.
type Claims ¶
Claims are the claims of a verified token (or an introspection answer), as 9in sent them: numbers are float64, lists []any, objects map[string]any. The methods read the common ones.
Example ¶
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
nine "github.com/9in-io/go-sdk"
)
func main() {
var claims nine.Claims
_ = json.NewDecoder(strings.NewReader(`{"sub":"usr_8k2","client_id":"app_1","scope":"openid orders:read","exp":1794203600,"aud":"https://api.acme.com"}`)).Decode(&claims)
fmt.Println(claims.Subject(), claims.Scopes(), claims.HasScope("orders:read"), claims.Audience(), claims.ExpiresAt().UTC().Format(time.RFC3339))
}
Output: usr_8k2 [openid orders:read] true [https://api.acme.com] 2026-11-09T05:53:20Z
func ClaimsFrom ¶
ClaimsFrom returns the access token claims RequireAuth put in the request context, or nil.
func (Claims) Audience ¶
Audience is the aud claim (a single audience is returned as a one-item list).
func (Claims) IsMachine ¶
IsMachine reports whether this is a client-credentials token: its subject is the application itself (sub equals client_id) and it has no session.
func (Claims) Subject ¶
Subject is the sub claim: the user's id, or the client ID for a client-credentials token.
type ClientCredentials ¶
type ClientCredentials struct {
// contains filtered or unexported fields
}
ClientCredentials gets access tokens for a service itself (no user) with the client credentials grant, and caches each until shortly before it expires. Concurrent callers share one request. Safe for concurrent use.
Example ¶
package main
import (
"log"
"net/http"
"os"
"time"
nine "github.com/9in-io/go-sdk"
)
func main() {
service, err := nine.NewClientCredentials(nine.ClientCredentialsConfig{
Issuer: "https://acme.9in.io",
ClientID: os.Getenv("NINE_CLIENT_ID"),
ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
Audience: "https://api.acme.com",
})
if err != nil {
log.Fatal(err)
}
// Every request carries a cached, renewed-before-expiry access token.
client := service.HTTPClient(&http.Client{Timeout: 10 * time.Second})
res, err := client.Get("https://api.acme.com/reports")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
}
Output:
func NewClientCredentials ¶
func NewClientCredentials(cfg ClientCredentialsConfig) (*ClientCredentials, error)
NewClientCredentials returns a ClientCredentials token source.
func (*ClientCredentials) HTTPClient ¶
func (c *ClientCredentials) HTTPClient(base *http.Client) *http.Client
HTTPClient returns a copy of base (or of http.DefaultClient) that adds "Authorization: Bearer <token>" to every request. Use it only for the API the token is for.
func (*ClientCredentials) Invalidate ¶
func (c *ClientCredentials) Invalidate()
Invalidate forgets the cached token, so the next call gets a new one (after a 401 from your API, say).
type ClientCredentialsConfig ¶
type ClientCredentialsConfig struct {
// Issuer is your tenant's issuer.
Issuer string
// ClientID and ClientSecret are a confidential (machine-to-machine) application.
ClientID string
ClientSecret string
// Audience is the API to call; leave empty for the Management API.
Audience string
// Scopes to request; empty means every scope the application was granted for Audience.
Scopes []string
// HTTPClient is used for the token requests. Default: a client with a 10-second timeout.
HTTPClient *http.Client
// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
AllowInsecureIssuer bool
}
ClientCredentialsConfig configures a ClientCredentials token source.
func ClientCredentialsConfigFromEnv ¶
func ClientCredentialsConfigFromEnv() ClientCredentialsConfig
ClientCredentialsConfigFromEnv returns a ClientCredentialsConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_AUDIENCE and NINE_ALLOW_INSECURE_ISSUER.
type ClientCredentialsOptions ¶
type ClientCredentialsOptions struct {
// Audience is the API to get a token for; leave empty for the Management API.
Audience string
// Scope is space-separated; empty means every scope the application was granted.
Scope string
}
ClientCredentialsOptions are the parameters of a client-credentials request.
type DeviceAuth ¶
type DeviceAuth struct {
// contains filtered or unexported fields
}
DeviceAuth signs users in on devices without a browser or keyboard (CLIs, TVs) with the device authorization grant (RFC 8628): the device shows a short code, the user enters it on their phone or computer, and the device receives tokens once they approve. Safe for concurrent use.
code, _ := device.Start(ctx)
fmt.Printf("Open %s and enter %s\n", code.VerificationURI, code.UserCode)
tokens, err := device.Wait(ctx, code)
Example ¶
package main
import (
"context"
"fmt"
"log"
nine "github.com/9in-io/go-sdk"
)
func main() {
device, err := nine.NewDeviceAuth(nine.DeviceAuthConfig{Issuer: "https://acme.9in.io", ClientID: "app_tv123"})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
code, err := device.Start(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Open %s and enter %s\n", code.VerificationURI, code.UserCode)
tokens, err := device.Wait(ctx, code) // polls until the user approves
if err != nil {
log.Fatal(err) // access_denied, expired_token…
}
fmt.Println("signed in as", tokens.Claims.Subject())
}
Output:
func NewDeviceAuth ¶
func NewDeviceAuth(cfg DeviceAuthConfig) (*DeviceAuth, error)
NewDeviceAuth returns a DeviceAuth.
func (*DeviceAuth) EnsureFresh ¶
func (d *DeviceAuth) EnsureFresh(ctx context.Context, tokens *TokenSet, leeway time.Duration) (*TokenSet, error)
EnsureFresh returns tokens unchanged while valid for at least leeway, else refreshed.
func (*DeviceAuth) Poll ¶
func (d *DeviceAuth) Poll(ctx context.Context, code *DeviceCode) (*TokenSet, error)
Poll asks once whether the user has approved. It fails with authorization_pending (keep polling), slow_down (poll less often), access_denied (the user declined) or expired_token (start over). On success a returned ID token is verified.
func (*DeviceAuth) Revoke ¶
func (d *DeviceAuth) Revoke(ctx context.Context, token, hint string) error
Revoke revokes a refresh token (hint "refresh_token", the default) or an access token.
func (*DeviceAuth) Start ¶
func (d *DeviceAuth) Start(ctx context.Context) (*DeviceCode, error)
Start asks 9in for a device code and a user code.
func (*DeviceAuth) UserInfo ¶
UserInfo returns the user's current claims from the userinfo endpoint.
func (*DeviceAuth) Wait ¶
func (d *DeviceAuth) Wait(ctx context.Context, code *DeviceCode) (*TokenSet, error)
Wait polls every code.Interval seconds until the user approves (and returns the tokens), declines (access_denied), the code expires (expired_token) or ctx ends. It slows down by 5 seconds whenever 9in asks it to.
type DeviceAuthConfig ¶
type DeviceAuthConfig struct {
// Issuer is your tenant's issuer.
Issuer string
// ClientID is a "TV & Device" application (a public client with the device code grant).
ClientID string
// ClientSecret is only for confidential applications that enable the device grant.
ClientSecret string
// Scopes default to openid, profile and offline_access.
Scopes []string
// Audience is an API identifier, to get access tokens for that API.
Audience string
// Leeway is the clock skew allowed when checking ID tokens. Default 30 seconds.
Leeway time.Duration
// HTTPClient is used for every call to 9in. Default: a client with a 10-second timeout.
HTTPClient *http.Client
// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
AllowInsecureIssuer bool
}
DeviceAuthConfig configures a DeviceAuth.
type DeviceCode ¶
type DeviceCode struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
// ExpiresIn and Interval are seconds, as 9in sent them.
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
// ExpiresAt is when the code stops working.
ExpiresAt time.Time `json:"expires_at"`
}
DeviceCode is what DeviceAuth.Start returns: show the user VerificationURI and UserCode (or a QR code of VerificationURIComplete, which fills the code in).
type Discovery ¶
type Discovery struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
JWKSURI string `json:"jwks_uri"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
EndSessionEndpoint string `json:"end_session_endpoint,omitempty"`
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"`
AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
}
Discovery is your tenant's OpenID Connect discovery document (<issuer>/.well-known/openid-configuration), with the fields this package uses.
type Error ¶
type Error struct {
// Code is the error code, e.g. "invalid_token".
Code string
// Description says what went wrong, for people (never contains a token or secret).
Description string
// Status is the HTTP status: the one 9in answered with, or the one to answer with
// (401 for invalid_token, 403 for insufficient_scope). 0 when there is none.
Status int
// Details is the "details" member of a Management API error body, when there is one
// (for invalid_user, a list of {path, message}).
Details any
// contains filtered or unexported fields
}
Error is the error every failure in this package is reported with. Code is an OAuth-style error code ("invalid_token", "insufficient_scope", "invalid_grant", "insecure_issuer", …), passed through unchanged when it comes from 9in. Status is the HTTP status that goes with it (0 when there is none).
Use errors.As to read it, or errors.Is with one of the Err values below to test for a code:
if errors.Is(err, nine.ErrInsufficientScope) { … }
var e *nine.Error
if errors.As(err, &e) && e.Code == "identifier_taken" { … }
Example ¶
package main
import (
"errors"
"fmt"
nine "github.com/9in-io/go-sdk"
)
func main() {
err := error(&nine.Error{Code: "insufficient_scope", Description: "missing orders:write", Status: 403})
var e *nine.Error
if errors.As(err, &e) {
fmt.Println(e.Code, e.Status)
}
fmt.Println(errors.Is(err, nine.ErrInsufficientScope), errors.Is(err, nine.ErrInvalidToken))
}
Output: insufficient_scope 403 true false
type EventDeduplicator ¶
type EventDeduplicator struct {
// Store keeps the ids (required). Its Add must be atomic.
Store EventStore
// TTL is how long a processed id is remembered. Default 3 days.
TTL time.Duration
// LockTTL is how long a running handler holds the id before another delivery may
// take over. Default 5 minutes.
LockTTL time.Duration
// Prefix starts every key. Default "9in:event:".
Prefix string
}
EventDeduplicator runs a handler at most once per event id. 9in keeps the id on every retry and redelivery, and retries until it gets a 2xx (for about a day).
func (*EventDeduplicator) Process ¶
func (d *EventDeduplicator) Process(ctx context.Context, eventID string, handler func(context.Context) error) (ProcessStatus, error)
Process claims eventID and runs handler:
- Processed: first delivery, handler succeeded (the id is then remembered for TTL).
- Duplicate: already processed; handler not run.
- InProgress: another delivery is running it; handler not run.
- handler failed (or panicked): the claim is released so 9in's retry runs it again, and the error is returned (or the panic continues).
When the handler succeeded but marking the id as done failed, it returns Processed with that error.
type EventStore ¶
type EventStore interface {
Add(ctx context.Context, key, value string, ttl time.Duration) (bool, error)
Get(ctx context.Context, key string) (value string, ok bool, err error)
Set(ctx context.Context, key, value string, ttl time.Duration) error
Delete(ctx context.Context, key string) error
}
EventStore is a key-value store for processing each event once. Add must be atomic: insert only when the key is absent or expired, and report whether it did. Use Redis SET NX EX, an SQL table with a unique key, or MemoryEventStore for one process.
type Identifier ¶
Identifier is how a user signs in: Type is "email", "username" or "phone".
type ImportIdentity ¶
type ImportIdentity struct {
Connection string `json:"connection"` // e.g. social:google
Subject string `json:"subject"`
}
ImportIdentity is a linked sign-in carried over by an import.
type ImportOptions ¶
type ImportOptions struct {
// OnConflict is "skip" (the default) or "update" when a user already exists.
OnConflict string
// Source labels the import in the activity log.
Source string
}
ImportOptions are the options of ImportUsers.
type ImportResult ¶
type ImportResult struct {
Index int `json:"index"`
OK bool `json:"ok"`
// Status is "created", "updated", "skipped" or "failed".
Status string `json:"status"`
ID string `json:"id,omitempty"`
Reason string `json:"reason,omitempty"`
Error string `json:"error,omitempty"`
Details any `json:"details,omitempty"`
}
ImportResult is the outcome of one import record, in the order given.
type ImportUser ¶
type ImportUser struct {
// ID keeps the id from your old system (letters, digits and | _ . : @ + -, max 128).
ID string `json:"id,omitempty"`
NewUser
Identities []ImportIdentity `json:"identities,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
LastLoginAt *time.Time `json:"last_login_at,omitempty"`
}
ImportUser is one record for ImportUsers: the fields of NewUser plus what an import may carry over.
type ListUsersOptions ¶
type ListUsersOptions struct {
// Query matches email, username, phone number and name (substring) or an exact id.
Query string
// Cursor is the NextCursor of the previous page.
Cursor string
// Limit is 1 to 200 (default 50).
Limit int
}
ListUsersOptions page and search the user list.
type Login ¶
type Login struct {
URL string
Pending *PendingLogin
}
Login is a sign-in that has started: send the browser to URL and keep Pending until the callback.
type LoginLinkOptions ¶
type LoginLinkOptions struct {
// ReturnTo must be a registered callback URL of one of your applications, or a path
// on the login domain.
ReturnTo string
// TTL is how long the link works (whole seconds).
TTL time.Duration
}
LoginLinkOptions are the options of CreateLoginLink.
type LoginOptions ¶
type LoginOptions struct {
// ReturnTo is a path on your site to come back to afterwards ("/dashboard"). Only a
// same-site path is kept ([SafeReturnPath]); it comes back in [TokenSet].ReturnTo.
ReturnTo string
// Screen "signup" opens the sign-up form (prompt=create).
Screen string
// Prompt is "login" (sign in again), "consent", "select_account", "none" (no UI:
// fails with login_required) or "create".
Prompt string
// LoginHint prefills the identifier.
LoginHint string
// Locale picks the language of the hosted pages (ui_locales), e.g. "de".
Locale string
// RedirectURI overrides the configured callback URL for this sign-in.
RedirectURI string
// Params are extra authorization parameters (max_age, …). They never replace
// response_type, client_id, redirect_uri, scope, state, nonce or PKCE.
Params map[string]string
}
LoginOptions are the choices for one sign-in.
type LogoutOptions ¶
type LogoutOptions struct {
// IDTokenHint identifies the session's application (an expired ID token is fine).
IDTokenHint string
// PostLogoutRedirectURI is where 9in sends the user afterwards: one of the
// application's allowed logout URLs.
PostLogoutRedirectURI string
// State is added to that redirect.
State string
}
LogoutOptions are the parameters of the end-session URL.
type MFAState ¶
type MFAState struct {
Enabled bool `json:"enabled"`
EnabledAt *time.Time `json:"enabled_at,omitempty"`
RecoveryCodesLeft *int `json:"recovery_codes_left,omitempty"`
}
MFAState is a user's two-factor state.
type ManagedIdentity ¶
type ManagedIdentity struct {
Connection string `json:"connection"`
Subject string `json:"subject"`
Profile map[string]any `json:"profile"`
CreatedAt time.Time `json:"created_at"`
}
ManagedIdentity is a linked sign-in of a user (social:google, enterprise:<id>, adapter…).
type ManagedSession ¶
type ManagedSession struct {
SID string `json:"sid"`
UserID string `json:"user_id"`
AuthTime time.Time `json:"auth_time"`
AMR []string `json:"amr"`
IP string `json:"ip"`
UserAgent string `json:"user_agent"`
CreatedAt time.Time `json:"created_at"`
LastSeenAt time.Time `json:"last_seen_at"`
ExpiresAt time.Time `json:"expires_at"`
}
ManagedSession is an active sign-in session; SID is the sid claim of its tokens.
type ManagedUser ¶
type ManagedUser struct {
ID string `json:"id"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
PhoneNumber string `json:"phone_number"`
PhoneNumberVerified bool `json:"phone_number_verified"`
Username string `json:"username"`
PreferredUsername string `json:"preferred_username"`
Name string `json:"name"`
GivenName string `json:"given_name"`
MiddleName string `json:"middle_name"`
FamilyName string `json:"family_name"`
Nickname string `json:"nickname"`
Gender string `json:"gender"`
Website string `json:"website"`
Picture string `json:"picture"`
Locale string `json:"locale"`
Zoneinfo string `json:"zoneinfo"`
Birthdate string `json:"birthdate"`
Blocked bool `json:"blocked"`
Metadata map[string]any `json:"metadata"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastLoginAt *time.Time `json:"last_login_at"`
LoginCount int `json:"login_count"`
}
ManagedUser is a user as the Management API and webhooks send it.
type ManagementClient ¶
type ManagementClient struct {
// contains filtered or unexported fields
}
ManagementClient calls the Management API (/api/v1) of one tenant environment: users, sessions, login links and imports. It gets client-credentials tokens itself, one per management scope (so an application granted only some scopes works), and caches each until shortly before it expires. Safe for concurrent use.
Wire data uses 9in's snake_case names in both directions. Errors are *Error with the API's error code (not_found, identifier_taken, invalid_user…), Status and Details.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
nine "github.com/9in-io/go-sdk"
)
func main() {
m, err := nine.NewManagementClient(nine.ManagementConfig{
Issuer: "https://acme.9in.io",
ClientID: os.Getenv("NINE_CLIENT_ID"), // an application with management scopes
ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
user, err := m.CreateUser(ctx, nine.NewUser{Email: "jane@acme.com", EmailVerified: true, Password: "a long passphrase"})
var e *nine.Error
if errors.As(err, &e) && e.Code == "identifier_taken" {
user, err = m.FindUserByEmail(ctx, "jane@acme.com")
}
if err != nil {
log.Fatal(err)
}
_, _ = m.UpdateUser(ctx, user.ID, nine.UserChanges{"metadata": map[string]any{"plan": "pro"}})
link, _ := m.CreateLoginLink(ctx, user.ID, nine.LoginLinkOptions{ReturnTo: "https://app.acme.com/nine/callback", TTL: 10 * time.Minute})
fmt.Println(link.URL)
}
Output:
func NewManagementClient ¶
func NewManagementClient(cfg ManagementConfig) (*ManagementClient, error)
NewManagementClient returns a ManagementClient.
func (*ManagementClient) BlockUser ¶
func (m *ManagementClient) BlockUser(ctx context.Context, id string) (*ManagedUser, error)
BlockUser blocks a user: their sessions end and their tokens stop working.
func (*ManagementClient) CreateLoginLink ¶
func (m *ManagementClient) CreateLoginLink(ctx context.Context, id string, opts LoginLinkOptions) (*LoginLink, error)
CreateLoginLink creates a single-use URL that signs the user in (magic links, handing a signed-in user over from your app). Two-factor authentication still applies.
func (*ManagementClient) CreateUser ¶
func (m *ManagementClient) CreateUser(ctx context.Context, user NewUser) (*ManagedUser, error)
CreateUser creates a user. A taken email, phone number or username fails with identifier_taken (409); bad fields with invalid_user (400, with Details).
func (*ManagementClient) DeleteUser ¶
func (m *ManagementClient) DeleteUser(ctx context.Context, id string) error
DeleteUser deletes a user.
func (*ManagementClient) FindUser ¶
func (m *ManagementClient) FindUser(ctx context.Context, field, value string) (*ManagedUser, error)
FindUser looks a user up by field "email", "phone_number" (E.164) or "username". Emails and usernames match case-insensitively. No match fails with not_found (404).
func (*ManagementClient) FindUserByEmail ¶
func (m *ManagementClient) FindUserByEmail(ctx context.Context, email string) (*ManagedUser, error)
FindUserByEmail is FindUser(ctx, "email", email).
func (*ManagementClient) GetUser ¶
func (m *ManagementClient) GetUser(ctx context.Context, id string) (*UserDetail, error)
GetUser returns a user with their identities, active sessions and two-factor state. An unknown id fails with not_found (404): test with errors.Is(err, nine.ErrNotFound).
func (*ManagementClient) ImportUsers ¶
func (m *ManagementClient) ImportUsers(ctx context.Context, users []ImportUser, opts ImportOptions) ([]ImportResult, error)
ImportUsers imports up to 500 users per call (50 with plain-text passwords). Records may keep their old id and carry password hashes, social identities and original dates. Results are per record, in order; one bad record doesn't stop the others.
func (*ManagementClient) ListUserSessions ¶
func (m *ManagementClient) ListUserSessions(ctx context.Context, id string) ([]ManagedSession, error)
ListUserSessions returns the user's active sessions, most recently used first.
func (*ManagementClient) ListUsers ¶
func (m *ManagementClient) ListUsers(ctx context.Context, opts ListUsersOptions) (*UserList, error)
ListUsers returns a page of users, newest first.
func (*ManagementClient) RevokeSession ¶
func (m *ManagementClient) RevokeSession(ctx context.Context, sid string) error
RevokeSession ends one session (its sid) and every token issued under it.
func (*ManagementClient) RevokeUserSessions ¶
RevokeUserSessions signs the user out everywhere and returns how many sessions ended.
func (*ManagementClient) UnblockUser ¶
func (m *ManagementClient) UnblockUser(ctx context.Context, id string) (*ManagedUser, error)
UnblockUser lets a blocked user sign in again.
func (*ManagementClient) UpdateUser ¶
func (m *ManagementClient) UpdateUser(ctx context.Context, id string, changes UserChanges) (*ManagedUser, error)
UpdateUser changes only the fields given and returns the updated user.
type ManagementConfig ¶
type ManagementConfig struct {
// Issuer is your tenant's issuer: https://acme.9in.io for production users,
// https://acme-sandbox.9in.io for the sandbox's, or your custom domain.
Issuer string
// ClientID and ClientSecret are a confidential application that was given management
// scopes (Applications → app → API Access → Management API).
ClientID string
ClientSecret string
// HTTPClient is used for every call. Default: a client with a 10-second timeout.
HTTPClient *http.Client
// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
AllowInsecureIssuer bool
}
ManagementConfig configures a ManagementClient.
func ManagementConfigFromEnv ¶
func ManagementConfigFromEnv() ManagementConfig
ManagementConfigFromEnv returns a ManagementConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET and NINE_ALLOW_INSECURE_ISSUER.
type MemoryAnswerCache ¶
type MemoryAnswerCache struct {
// contains filtered or unexported fields
}
MemoryAnswerCache is an in-memory, least-recently-used AnswerCache for one process.
func NewMemoryAnswerCache ¶
func NewMemoryAnswerCache(size int) *MemoryAnswerCache
NewMemoryAnswerCache returns an in-memory cache of at most size answers (default 10 000).
func (*MemoryAnswerCache) Clear ¶
func (c *MemoryAnswerCache) Clear(context.Context)
Clear implements AnswerCache.
func (*MemoryAnswerCache) Evict ¶
func (c *MemoryAnswerCache) Evict(_ context.Context, claim, value string) int
Evict implements AnswerCache.
func (*MemoryAnswerCache) Get ¶
func (c *MemoryAnswerCache) Get(_ context.Context, key string) (CachedAnswer, bool)
Get implements AnswerCache.
func (*MemoryAnswerCache) Len ¶
func (c *MemoryAnswerCache) Len() int
Len is the number of answers held (expired ones included until they are looked up).
func (*MemoryAnswerCache) Set ¶
func (c *MemoryAnswerCache) Set(_ context.Context, key string, answer CachedAnswer)
Set implements AnswerCache.
type MemoryEventStore ¶
type MemoryEventStore struct {
// contains filtered or unexported fields
}
MemoryEventStore is an in-memory EventStore for one process (tests, a single server).
func NewMemoryEventStore ¶
func NewMemoryEventStore() *MemoryEventStore
NewMemoryEventStore returns an empty MemoryEventStore.
func (*MemoryEventStore) Add ¶
func (s *MemoryEventStore) Add(_ context.Context, key, value string, ttl time.Duration) (bool, error)
Add implements EventStore.
func (*MemoryEventStore) Delete ¶
func (s *MemoryEventStore) Delete(_ context.Context, key string) error
Delete implements EventStore.
type Mode ¶
type Mode string
Mode is how a Verifier checks access tokens: the trade-off between speed and how quickly a revocation takes effect.
const ( // ModeLocal checks the signature and claims only. No calls to 9in per request; a // revoked token keeps working until it expires. ModeLocal Mode = "local" // ModeHybrid checks locally, then asks 9in once per token (introspection) and caches // the answer until a webhook says otherwise ([Verifier.HandleEvent]) or CacheTTL // passes. A refusal is cached until the token expires. ModeHybrid Mode = "hybrid" // ModeIntrospect asks 9in about every token on every call. ModeIntrospect Mode = "introspect" )
type NewUser ¶
type NewUser struct {
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
PhoneNumber string `json:"phone_number,omitempty"` // E.164, e.g. +447700900123
PhoneNumberVerified bool `json:"phone_number_verified,omitempty"`
Username string `json:"username,omitempty"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"`
Locale string `json:"locale,omitempty"`
Zoneinfo string `json:"zoneinfo,omitempty"`
Birthdate string `json:"birthdate,omitempty"` // YYYY-MM-DD
Blocked bool `json:"blocked,omitempty"`
// Metadata is stored on the user; custom profile fields live in metadata.fields.
Metadata map[string]any `json:"metadata,omitempty"`
// Password is a plain password (hashed with argon2id), or give PasswordHash.
Password string `json:"password,omitempty"`
// PasswordHash is an existing bcrypt, argon2, PBKDF2 or Firebase scrypt hash.
PasswordHash string `json:"password_hash,omitempty"`
}
NewUser is a user to create. At least one of Email, PhoneNumber or Username is required.
type PendingLogin ¶
type PendingLogin struct {
State string `json:"state"`
Nonce string `json:"nonce"`
Verifier string `json:"verifier"`
RedirectURI string `json:"redirect_uri"`
ReturnTo string `json:"return_to,omitempty"`
// CreatedAt is unix seconds.
CreatedAt int64 `json:"created_at"`
}
PendingLogin is what to keep between the redirect to 9in and the callback, for about 15 minutes. It holds the PKCE verifier: store it server-side or encrypted, and delete it when the callback arrives. It marshals to JSON.
type ProcessStatus ¶
type ProcessStatus string
ProcessStatus is the outcome of processing an event once.
const ( // Processed: the first delivery, and the handler succeeded. Answer 2xx. Processed ProcessStatus = "processed" // Duplicate: already processed. Answer 2xx so 9in stops retrying. Duplicate ProcessStatus = "duplicate" // InProgress: another delivery of the same event is still running. Answer 409 so 9in // tries again later. InProgress ProcessStatus = "in_progress" )
func ProcessEventOnce ¶
func ProcessEventOnce(ctx context.Context, store EventStore, eventID string, handler func(context.Context) error) (ProcessStatus, error)
ProcessEventOnce runs handler at most once per event id with the default TTLs. See EventDeduplicator.Process.
status, err := nine.ProcessEventOnce(ctx, store, event.ID, func(ctx context.Context) error { return handle(ctx, event) })
type TokenSet ¶
type TokenSet struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type,omitempty"`
// ExpiresAt is when the access token expires.
ExpiresAt time.Time `json:"expires_at"`
// RefreshToken comes with the offline_access scope. 9in rotates it: keep the new one
// after every refresh.
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
Scope string `json:"scope,omitempty"`
// Claims are the verified ID token's claims (sub, email, name, amr, sid…), nil
// without an ID token.
Claims Claims `json:"claims,omitempty"`
// ReturnTo is the path to send the user to after sign-in, from the pending login
// (only a same-site path is kept).
ReturnTo string `json:"return_to,omitempty"`
}
TokenSet is what a sign-in, a refresh or a client-credentials request returns. It marshals to JSON (snake_case keys), so you can keep it in a server-side session.
type User ¶
type User struct {
// Subject is the user's 9in id (the sub claim).
Subject string `json:"sub"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"`
PhoneNumber string `json:"phone_number,omitempty"`
Locale string `json:"locale,omitempty"`
// Claims are all of the user's claims (profile, custom fields, amr, auth_time…).
Claims Claims `json:"claims"`
}
User is the signed-in user of a WebApp, from the ID token.
func UserFrom ¶
UserFrom returns the signed-in user WebApp.Middleware or WebApp.RequireUser put in the request context, or nil.
type UserChanges ¶
UserChanges are the fields UpdateUser changes, with the API's names ("name", "phone_number", "email_verified", "metadata", "blocked", "password"…). A nil value clears a field. Metadata is replaced as a whole: read, merge, then send.
type UserDetail ¶
type UserDetail struct {
User ManagedUser `json:"user"`
Identities []ManagedIdentity `json:"identities"`
Sessions []ManagedSession `json:"sessions"`
HasPassword bool `json:"has_password"`
MFA MFAState `json:"mfa"`
}
UserDetail is what GetUser returns: the user with their identities, active sessions and two-factor state.
type UserList ¶
type UserList struct {
Users []ManagedUser `json:"users"`
NextCursor string `json:"next_cursor"`
Total int `json:"total"`
}
UserList is a page of users. Pass NextCursor back as the cursor for the next page; it is empty on the last page.
type UserQuery ¶
type UserQuery struct {
ID string
Identifier *Identifier
}
UserQuery is what 9in looks a user up by: ID (your own user id) or Identifier.
type Verifier ¶
type Verifier struct {
// contains filtered or unexported fields
}
Verifier verifies 9in access tokens for your API. Create one at startup and share it: it caches your tenant's keys (and, in hybrid mode, 9in's answers), and is safe for concurrent use.
Every algorithm of 9in's key library is accepted: RS256/384/512, PS256/384/512, ES256, ES384 and EdDSA against the tenant's JWKS, and HS256/384/512 with the API's shared secret. Tokens must be access tokens (typ at+jwt); when the JWKS key names an algorithm, the token must use exactly that one, and the key type must fit it. The issuer, expiry (exp, nbf), audience and required scopes are checked. Keys are cached for ten minutes and fetched again once when a token names an unknown key.
func NewVerifier ¶
func NewVerifier(cfg VerifierConfig) (*Verifier, error)
NewVerifier returns a Verifier. It fails for a malformed or insecure issuer, an unknown mode, or hybrid/introspect mode without client credentials.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
nine "github.com/9in-io/go-sdk"
)
func main() {
verifier, err := nine.NewVerifier(nine.VerifierConfig{
Issuer: "https://acme.9in.io",
Audience: "https://api.acme.com",
})
if err != nil {
log.Fatal(err)
}
claims, err := verifier.Verify(context.Background(), "eyJhbGciOi…", "orders:read")
switch {
case errors.Is(err, nine.ErrInsufficientScope): // 403
case errors.Is(err, nine.ErrInvalidToken): // 401
case err != nil: // 9in unreachable
default:
fmt.Println(claims.Subject(), claims.Scopes())
}
}
Output:
Example (Hybrid) ¶
Hybrid verification: revocations take effect as soon as the webhook arrives.
package main
import (
"log"
"net/http"
"os"
"time"
nine "github.com/9in-io/go-sdk"
)
func main() {
verifier, err := nine.NewVerifier(nine.VerifierConfig{
Issuer: "https://acme.9in.io",
Audience: "https://api.acme.com",
ClientID: os.Getenv("NINE_CLIENT_ID"), // a confidential application:
ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
// Mode: nine.ModeHybrid is the default with client credentials.
CacheTTL: 5 * time.Minute,
})
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/api/orders", nine.RequireAuth(verifier, "orders:read")(http.HandlerFunc(listOrders)))
// Subscribed to token.revoked, session.revoked and user.* events.
mux.Handle("/nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
Secret: os.Getenv("NINE_WEBHOOK_SECRET"),
Verifier: verifier,
}))
}
func listOrders(w http.ResponseWriter, r *http.Request) {}
Output:
func (*Verifier) HandleEvent ¶
func (v *Verifier) HandleEvent(ctx context.Context, event *WebhookEvent) int
HandleEvent drops the cached hybrid answers a webhook event makes stale and returns how many: token.revoked (an access token) by jti, session.revoked by sid, and user.sessions_revoked, user.deleted, user.updated and user.password_changed by user. Subscribe your webhook endpoint to those events and pass every verified event here (WebhookConfig.Verifier does it for you).
func (*Verifier) Verify ¶
Verify verifies an access token (or an Authorization header value, "Bearer …") and returns its claims. Each scope argument may hold several space-separated scopes; all must be granted.
It fails with invalid_token (Status 401) for a bad token and insufficient_scope (403) when a scope is missing. Other errors (9in unreachable, introspection refused) are your server's problem, not the caller's.
func (*Verifier) VerifyIDToken ¶
func (v *Verifier) VerifyIDToken(ctx context.Context, idToken, clientID, nonce string) (Claims, error)
VerifyIDToken verifies an ID token issued to clientID: the signature (asymmetric keys only: 9in signs ID tokens with the tenant's default key), issuer, audience (and azp when there are several audiences), expiry, the nonce when expected is not empty, and that it is not an access token. It fails with invalid_id_token.
type VerifierConfig ¶
type VerifierConfig struct {
// Issuer is your tenant's issuer, exactly as in the tokens' iss claim, e.g.
// https://acme.9in.io or your custom login domain.
Issuer string
// Audience is your API's identifier: tokens must have it in aud. Leave empty to
// accept any audience (not recommended).
Audience string
// Audiences are more API identifiers to accept, besides Audience.
Audiences []string
// Secret is your API's shared secret, for APIs that sign with an HMAC key
// (HS256/384/512) from the console's key library. JWKS keys need nothing.
Secret string
// Mode defaults to ModeHybrid when ClientID and ClientSecret are set, else ModeLocal.
Mode Mode
// ClientID and ClientSecret are a confidential application of the tenant, used for
// introspection (ModeHybrid, ModeIntrospect and opaque tokens).
ClientID string
ClientSecret string
// CacheTTL is the longest a hybrid answer is trusted without news from 9in.
// Default 5 minutes. An answer is never kept past the token's expiry.
CacheTTL time.Duration
// Cache keeps hybrid answers. Default: in memory, per process, CacheSize entries.
// Use a shared AnswerCache when several processes should see the same evictions.
Cache AnswerCache
// CacheSize is the most answers the default cache keeps (default 10 000; the least
// recently used go first).
CacheSize int
// Leeway is the clock skew allowed for exp and nbf. Default 30 seconds.
Leeway time.Duration
// HTTPClient is used for discovery, JWKS and introspection. Default: a client with a
// 10-second timeout. Redirects are never followed.
HTTPClient *http.Client
// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
AllowInsecureIssuer bool
}
VerifierConfig configures a Verifier.
func VerifierConfigFromEnv ¶
func VerifierConfigFromEnv() VerifierConfig
VerifierConfigFromEnv returns a VerifierConfig from NINE_ISSUER, NINE_AUDIENCE, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_API_SECRET and NINE_ALLOW_INSECURE_ISSUER. With a client ID and secret the verifier runs in hybrid mode.
type WebApp ¶
type WebApp struct {
// contains filtered or unexported fields
}
WebApp is sign-in for a server-rendered Go web app, ready to mount: the /nine/login, /nine/signup, /nine/callback and /nine/logout routes, an encrypted cookie session (AES-256-GCM; no server-side storage), token refresh with rotation, and [RequireUser] middleware. It works with any router that speaks http.Handler.
app, err := nine.NewWebApp(nine.WebAppConfigFromEnv())
mux.Handle("/nine/", app)
mux.Handle("/dashboard", app.RequireUser(dashboard))
In a handler, UserFrom returns the signed-in user and WebApp.AccessToken a valid access token for your API. Safe for concurrent use.
func NewWebApp ¶
func NewWebApp(cfg WebAppConfig) (*WebApp, error)
NewWebApp returns a WebApp. It fails when the issuer, client ID or secret is missing or invalid.
Example ¶
package main
import (
"log"
"net/http"
"os"
nine "github.com/9in-io/go-sdk"
)
func main() {
app, err := nine.NewWebApp(nine.WebAppConfig{
Issuer: "https://acme.9in.io",
ClientID: "app_7f3k2m9q",
ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
Secret: os.Getenv("NINE_SECRET"), // encrypts the session cookie
BaseURL: "https://app.acme.com", // callback: https://app.acme.com/nine/callback
Audience: "https://api.acme.com", // access tokens for your API
})
if err != nil {
log.Fatal(err)
}
http.Handle("/nine/", app)
http.Handle("/orders", app.RequireUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := app.AccessToken(w, r) // refreshed (and rotated) when needed
if err != nil {
http.Redirect(w, r, "/nine/login", http.StatusFound)
return
}
req, _ := http.NewRequestWithContext(r.Context(), "GET", "https://api.acme.com/orders", nil)
req.Header.Set("Authorization", "Bearer "+token)
// … call your API
})))
}
Output:
func (*WebApp) AccessToken ¶
AccessToken returns a valid access token for the signed-in user (for your API, with Audience set), refreshing it when it expires within RefreshLeeway and saving the rotated refresh token in the cookie. Call it before writing the response body, so the cookie can still be set. It fails with login_required (401) when there is no session or it ended.
func (*WebApp) Auth ¶
func (a *WebApp) Auth() *WebAppAuth
Auth is the underlying WebAppAuth (refresh, revoke, userinfo, client credentials).
func (*WebApp) Callback ¶
func (a *WebApp) Callback(w http.ResponseWriter, r *http.Request)
Callback finishes a sign-in (the /nine/callback route): it checks the callback against the sign-in cookie, starts the session and redirects to return_to.
func (*WebApp) Login ¶
func (a *WebApp) Login(w http.ResponseWriter, r *http.Request)
Login starts a sign-in (the /nine/login route). Query parameters: return_to (a path on your site), screen=signup, prompt, login_hint, locale.
func (*WebApp) Logout ¶
func (a *WebApp) Logout(w http.ResponseWriter, r *http.Request)
Logout signs the user out (the /nine/logout route, GET or POST): it clears the session, revokes the refresh token and sends the browser to 9in's end-session URL, which comes back to return_to (a path) or AfterSignOutPath. local=1 skips ending the 9in session.
func (*WebApp) Middleware ¶
Middleware reads the session for every request it wraps: UserFrom returns the user (nil when signed out), and the access token is refreshed before it expires. Signed-out visitors go through; use WebApp.RequireUser to keep them out.
func (*WebApp) RequireUser ¶
RequireUser is WebApp.Middleware for pages that need a signed-in user. Signed-out visitors are sent to the sign-in page and brought back afterwards; requests that aren't page navigations (fetch, API calls) get 401 JSON instead.
func (*WebApp) ServeHTTP ¶
func (a *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves the sign-in routes under BasePath: GET login, GET signup, GET callback, and GET or POST logout. Anything else is 404.
type WebAppAuth ¶
type WebAppAuth struct {
// contains filtered or unexported fields
}
WebAppAuth signs users in to a server-side web app: the authorization code flow with PKCE (S256), state and nonce, the RFC 9207 iss check, and the ID token verified against your tenant's keys. It also refreshes tokens (9in rotates refresh tokens), revokes them, builds the logout URL, reads userinfo and gets client-credentials tokens.
You keep the PendingLogin between WebAppAuth.CreateLogin and WebAppAuth.HandleCallback (in the user's session, or an encrypted cookie) and the TokenSet afterwards. WebApp does all of that for you. Safe for concurrent use.
Example ¶
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
nine "github.com/9in-io/go-sdk"
)
func main() {
auth, err := nine.NewWebAppAuth(nine.WebAppAuthConfig{
Issuer: "https://acme.9in.io",
ClientID: "app_7f3k2m9q",
ClientSecret: os.Getenv("NINE_CLIENT_SECRET"),
RedirectURI: "https://app.acme.com/nine/callback",
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
// /nine/login: keep login.Pending (server-side session, or encrypted) and redirect.
login, err := auth.CreateLogin(ctx, nine.LoginOptions{ReturnTo: "/dashboard"})
if err != nil {
log.Fatal(err)
}
fmt.Println("redirect to", login.URL)
// /nine/callback: checks state, iss and PKCE, and verifies the ID token.
var r *http.Request // the callback request
tokens, err := auth.HandleCallback(ctx, r.URL.Query(), login.Pending)
if err != nil {
log.Fatal(err)
}
fmt.Println(tokens.Claims.Subject(), tokens.Claims.String("email"), tokens.ReturnTo)
// Later: refresh before expiry and keep the result (9in rotates refresh tokens).
tokens, err = auth.EnsureFresh(ctx, tokens, time.Minute)
if err != nil {
log.Fatal(err)
}
_ = tokens
}
Output:
func NewWebAppAuth ¶
func NewWebAppAuth(cfg WebAppAuthConfig) (*WebAppAuth, error)
NewWebAppAuth returns a WebAppAuth. It fails when the issuer or client ID is missing, or the issuer is malformed or not https.
func (*WebAppAuth) ClientCredentials ¶
func (a *WebAppAuth) ClientCredentials(ctx context.Context, opts ClientCredentialsOptions) (*TokenSet, error)
ClientCredentials gets a token for the application itself (no user), for your own API (opts.Audience) or the Management API. Confidential applications only. For a cached, self-refreshing token use ClientCredentials instead.
func (*WebAppAuth) ClientID ¶
func (a *WebAppAuth) ClientID() string
ClientID is the application's client ID.
func (*WebAppAuth) CreateLogin ¶
func (a *WebAppAuth) CreateLogin(ctx context.Context, opts LoginOptions) (*Login, error)
CreateLogin starts a sign-in: it returns the URL of your tenant's hosted sign-in page and the PendingLogin to keep until the callback.
func (*WebAppAuth) Discovery ¶
func (a *WebAppAuth) Discovery(ctx context.Context) (*Discovery, error)
Discovery returns your tenant's discovery document (cached).
func (*WebAppAuth) EnsureFresh ¶
func (a *WebAppAuth) EnsureFresh(ctx context.Context, tokens *TokenSet, leeway time.Duration) (*TokenSet, error)
EnsureFresh returns tokens unchanged (the same pointer) while the access token is valid for at least leeway, and refreshed tokens otherwise (keeping the ID token, claims and ReturnTo when the refresh doesn't replace them). Save the result.
func (*WebAppAuth) HandleCallback ¶
func (a *WebAppAuth) HandleCallback(ctx context.Context, query url.Values, pending *PendingLogin) (*TokenSet, error)
HandleCallback finishes a sign-in on your callback URL. query is the callback's query (r.URL.Query()), pending what CreateLogin returned. It checks the error parameter, the pending login's age (15 minutes), the state (in constant time, and only once), the iss parameter (RFC 9207), exchanges the code with the PKCE verifier and verifies the ID token (signature, issuer, audience, expiry, nonce).
Errors: the OAuth error from 9in (access_denied when the user cancelled, login_required for prompt=none…), invalid_state, invalid_issuer, missing_code, invalid_grant and invalid_id_token.
func (*WebAppAuth) LogoutURL ¶
func (a *WebAppAuth) LogoutURL(ctx context.Context, opts LogoutOptions) (string, error)
LogoutURL is the URL that ends the session at 9in (RP-initiated logout) and returns to opts.PostLogoutRedirectURI, which must be an allowed logout URL of the application.
func (*WebAppAuth) Refresh ¶
Refresh exchanges a refresh token for new tokens. 9in rotates refresh tokens: keep the RefreshToken of the result (the old one is kept when 9in sends none). When 9in sends a new ID token it is verified and its claims are in Claims.
func (*WebAppAuth) Revoke ¶
func (a *WebAppAuth) Revoke(ctx context.Context, token, hint string) error
Revoke revokes a refresh token (and its whole rotation family; hint "refresh_token", the default) or an access token (hint "access_token"). 9in answers success for unknown tokens, so an error is a real failure such as invalid_client.
func (*WebAppAuth) UserInfo ¶
UserInfo returns the user's current claims from the userinfo endpoint. A revoked or expired token gets invalid_token.
func (*WebAppAuth) VerifyIDToken ¶
VerifyIDToken verifies an ID token issued to this application (nonce: the one sent with the sign-in, or "" to skip that check).
type WebAppAuthConfig ¶
type WebAppAuthConfig struct {
// Issuer is your tenant's issuer, e.g. https://acme.9in.io or your custom login domain.
Issuer string
// ClientID is the application's client ID.
ClientID string
// ClientSecret is set for confidential applications (sent with HTTP Basic,
// client_secret_basic). Leave it empty for public ones, which rely on PKCE alone.
ClientSecret string
// RedirectURI is your callback URL, as registered on the application. It can also be
// given per sign-in ([LoginOptions].RedirectURI).
RedirectURI string
// Scopes default to [DefaultScopes].
Scopes []string
// Audience is an API identifier, to get access tokens for that API.
Audience string
// Leeway is the clock skew allowed when checking ID tokens. Default 30 seconds.
Leeway time.Duration
// HTTPClient is used for every call to 9in. Default: a client with a 10-second
// timeout. Redirects are never followed.
HTTPClient *http.Client
// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
AllowInsecureIssuer bool
}
WebAppAuthConfig configures a WebAppAuth.
func WebAppAuthConfigFromEnv ¶
func WebAppAuthConfigFromEnv() WebAppAuthConfig
WebAppAuthConfigFromEnv returns a WebAppAuthConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI, NINE_AUDIENCE and NINE_ALLOW_INSECURE_ISSUER.
type WebAppConfig ¶
type WebAppConfig struct {
// Issuer is your tenant's issuer, e.g. https://acme.9in.io (NINE_ISSUER).
Issuer string
// ClientID is the application's client ID (NINE_CLIENT_ID).
ClientID string
// ClientSecret is set for a confidential application (NINE_CLIENT_SECRET). Leave it
// empty for a public one.
ClientSecret string
// Secret encrypts the session and sign-in cookies (NINE_SECRET): 32 characters or
// more, e.g. from `openssl rand -base64 32`.
Secret string
// Secrets are older secrets that still decrypt cookies while you rotate.
Secrets []string
// BaseURL is your app's URL, e.g. https://app.acme.com (NINE_BASE_URL). The callback
// URL is BaseURL + BasePath + "/callback". Default: the scheme and host of each
// request; set it in production, especially behind a proxy.
BaseURL string
// BasePath is where the routes are mounted. Default "/nine": /nine/login,
// /nine/signup, /nine/callback and /nine/logout. "/" mounts them at the root.
BasePath string
// Scopes default to [DefaultScopes] (offline_access gives a refresh token).
Scopes []string
// Audience is an API identifier, to get access tokens for that API (NINE_AUDIENCE).
Audience string
// CookieName is the session cookie's name. Default "nine_session".
CookieName string
// SessionMaxAge is how long a session lasts without being used. Default 30 days;
// each token refresh starts it again.
SessionMaxAge time.Duration
// RefreshLeeway is how long before expiry the access token is refreshed. Default 60 seconds.
RefreshLeeway time.Duration
// AfterSignInPath is where users land after sign-in when no return_to was given.
// Default "/".
AfterSignInPath string
// AfterSignOutPath is where users land after sign-out. BaseURL + this path must be
// an allowed logout URL of the application. Default "/".
AfterSignOutPath string
// OnError writes the answer for a failed sign-in (access_denied when the user
// cancels, say) or 9in being unreachable. Default: a plain-text error page.
OnError func(w http.ResponseWriter, r *http.Request, err error)
// HTTPClient is used for every call to 9in. Default: a client with a 10-second timeout.
HTTPClient *http.Client
// AllowInsecureIssuer accepts a plain-http issuer other than localhost (development only).
AllowInsecureIssuer bool
}
WebAppConfig configures a WebApp.
func WebAppConfigFromEnv ¶
func WebAppConfigFromEnv() WebAppConfig
WebAppConfigFromEnv returns a WebAppConfig from NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_SECRET (comma-separated to rotate: the first encrypts), NINE_BASE_URL, NINE_AUDIENCE and NINE_ALLOW_INSECURE_ISSUER.
type WebhookConfig ¶
type WebhookConfig struct {
// Secret is the endpoint's signing secret (NINE_WEBHOOK_SECRET).
Secret string
// Secrets are more secrets accepted while you rotate.
Secrets []string
// Handle is called once per event (after verification and de-duplication). Return
// an error to have 9in retry the delivery later.
Handle func(ctx context.Context, event *WebhookEvent) error
// Store remembers processed event ids so each event is handled once. Default: in
// memory (one process). With several instances, use a shared store.
Store EventStore
// TTL is how long processed ids are remembered. Default 3 days.
TTL time.Duration
// Verifier is a hybrid verifier to keep current: every verified event goes to its
// HandleEvent, so token.revoked, session.revoked and user.* evict cached answers.
Verifier *Verifier
// Path is the path 9in posts to, when a proxy rewrites it before it reaches you.
// Default: the request path as received.
Path string
// Tolerance is the signature timestamp tolerance. Default 5 minutes.
Tolerance time.Duration
// OnError is told about a failed Handle (the delivery gets a 500 and 9in retries) and
// about store failures. Optional.
OnError func(r *http.Request, err error)
}
WebhookConfig configures WebhookHandler.
type WebhookEvent ¶
type WebhookEvent struct {
ID string `json:"id"`
EventType string `json:"event_type"`
CreatedAt time.Time `json:"created_at"`
// Tenant is the tenant id (tnt_…).
Tenant string `json:"tenant"`
// Environment is "production" or "sandbox".
Environment string `json:"environment"`
Data map[string]any `json:"data"`
}
WebhookEvent is a webhook from 9in. Data carries the event's details plus "user", the user the event is about (the Management API user object, or nil when there is none; for user.deleted, the user as it was just before the deletion). ID is the same on every retry and redelivery.
func VerifyWebhook ¶
func VerifyWebhook(secrets []string, body []byte, signature, path string) (*WebhookEvent, error)
VerifyWebhook checks a webhook's 9in-signature header against the raw body and the path 9in posted to (r.URL.Path, or what it was before a proxy rewrote it), with any of secrets (several while you rotate), and returns the event. It fails with invalid_signature (401), or invalid_payload (400) when the body isn't an event.
Example ¶
package main
import (
"context"
"net/http"
"os"
nine "github.com/9in-io/go-sdk"
)
func main() {
http.HandleFunc("POST /nine/webhook", func(w http.ResponseWriter, r *http.Request) {
event, err := nine.VerifyWebhookRequest(r, os.Getenv("NINE_WEBHOOK_SECRET"))
if err != nil {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
status, err := nine.ProcessEventOnce(r.Context(), store, event.ID, func(ctx context.Context) error {
return handle(ctx, event)
})
switch {
case status == nine.InProgress:
w.WriteHeader(http.StatusConflict) // 9in retries later
case err != nil:
w.WriteHeader(http.StatusInternalServerError) // released: 9in retries
default:
w.WriteHeader(http.StatusNoContent)
}
})
}
var store = nine.NewMemoryEventStore()
func handle(context.Context, *nine.WebhookEvent) error { return nil }
Output:
func VerifyWebhookRequest ¶
func VerifyWebhookRequest(r *http.Request, secrets ...string) (*WebhookEvent, error)
VerifyWebhookRequest reads and verifies a webhook request (POST, signature over the raw body and the request path as sent). It consumes r.Body.
func (*WebhookEvent) User ¶
func (e *WebhookEvent) User() (*ManagedUser, error)
User decodes data.user into a ManagedUser; nil when the event is about no user.
func (*WebhookEvent) UserID ¶
func (e *WebhookEvent) UserID() string
UserID is the id of the user the event is about (data.user.id), or "".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
adapter
command
Command adapter keeps users in your own database: it serves the adapter protocol endpoints 9in calls (…/authenticate, …/user, …/event) over an in-memory user list.
|
Command adapter keeps users in your own database: it serves the adapter protocol endpoints 9in calls (…/authenticate, …/user, …/event) over an in-memory user list. |
|
api
command
Command api is an API protected with 9in access tokens, with a webhook endpoint that keeps hybrid verification current.
|
Command api is an API protected with 9in access tokens, with a webhook endpoint that keeps hybrid verification current. |
|
device
command
Command device signs in from a terminal with the device flow (RFC 8628).
|
Command device signs in from a terminal with the device flow (RFC 8628). |
|
webapp
command
Command webapp is a server-rendered web app that signs users in with 9in.
|
Command webapp is a server-rendered web app that signs users in with 9in. |