# Go

> Sign users in, protect APIs and handle webhooks from Go with the 9in SDK: net/http middleware, an encrypted session, the device flow.

Source: https://9in.io/docs/go/

Go apps use the official SDK, [`github.com/9in-io/go-sdk`](https://github.com/9in-io/go-sdk): sign-in for server-rendered apps with an encrypted cookie session, `net/http` middleware for APIs, the Management API, the adapter protocol, webhooks, the device flow and client credentials. It uses only the standard library, needs Go 1.23 or later, and works with any router that speaks `http.Handler` (`net/http`, chi, gin, echo).

```bash
go get github.com/9in-io/go-sdk
```

```go
import nine "github.com/9in-io/go-sdk"
```

## Sign users in

Web apps sign users in as a **confidential client** (see [Server-rendered apps](https://9in.io/docs/server-apps/) for how that works). Create the application first: **Applications → Create application → Regular Web App**, with `https://app.acme.com/nine/callback` as a callback URL and `https://app.acme.com/` as a logout URL, then set:

```bash
NINE_ISSUER=https://acme.9in.io          # or your custom login domain
NINE_CLIENT_ID=app_…
NINE_CLIENT_SECRET=…
NINE_SECRET=…                            # 32+ characters: openssl rand -base64 32 (encrypts the session cookie)
NINE_BASE_URL=https://app.acme.com       # http://localhost:3000 in development
# NINE_AUDIENCE=https://api.acme.com     # access tokens for your own API
```

```go
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()) // Subject, Email, Name, … and every claim in Claims
	fmt.Fprintf(w, "Hello %s", user.Name)
})))
```

Link to `/nine/login?return_to=/dashboard` (add `screen=signup` for the sign-up form) and `/nine/logout`, which revokes the refresh token and ends the 9in session. The session is an encrypted cookie (AES-256-GCM), so there is no server-side storage. Access tokens are refreshed before they expire and the rotated refresh token is saved; `app.AccessToken(w, r)` returns one for your API.

To keep the session yourself, use `nine.WebAppAuth`: `CreateLogin` returns the URL and a `PendingLogin` to keep until the callback, `HandleCallback(ctx, r.URL.Query(), pending)` checks state, `iss` and PKCE and verifies the ID token, and `EnsureFresh` refreshes tokens when needed (refresh tokens rotate, so save the set you get back).

## Protect an API

```go
verifier, err := nine.NewVerifier(nine.VerifierConfig{
	Issuer:       "https://acme.9in.io",
	Audience:     "https://api.acme.com",
	ClientID:     os.Getenv("NINE_CLIENT_ID"),     // with a confidential application's credentials,
	ClientSecret: os.Getenv("NINE_CLIENT_SECRET"), // tokens are checked in hybrid mode
})
mux.Handle("GET /api/orders", nine.RequireAuth(verifier, "orders:read")(orders))
// in the handler: nine.ClaimsFrom(r.Context()).Subject()

mux.Handle("POST /nine/webhook", nine.WebhookHandler(nine.WebhookConfig{
	Secret:   os.Getenv("NINE_WEBHOOK_SECRET"),
	Verifier: verifier, // token.revoked, session.revoked and user.* events evict cached answers
}))
```

`RequireAuth` answers 401 `invalid_token` or 403 `insufficient_scope`. Without client credentials the verifier checks tokens locally only, with every algorithm of the key library (`Secret` for HMAC keys). With them, it introspects each token once and caches the answer until a webhook or `CacheTTL` says otherwise, so a revoked token stops working at once ([hybrid verification](https://9in.io/docs/protecting-apis/)). Opaque tokens are always introspected.

With several processes, set `Store` in `VerifierConfig` (and `WebhookConfig`) to a store they all share, such as Redis: the process that receives a revocation webhook writes a small marker every process checks, so the revocation reaches them all. A `nine.Store` has four methods (`Get`, `Set`, an atomic `Add`, `Delete`); the [README](https://github.com/9in-io/go-sdk#several-processes-a-shared-store) has a Redis version to copy.

## Manage users, webhooks and your own database

- `nine.NewManagementClient(…)` covers the [Management API](https://9in.io/docs/reference/management-api/): users, sessions, login links and imports, with 9in's snake_case field names.
- `nine.WebhookHandler` verifies [webhooks](https://9in.io/docs/webhooks/), runs your function once per event (409 while a duplicate is in progress) and answers 204. Pass a shared `Store` when you run several instances.
- `nine.AdapterHandler` serves the [adapter protocol](https://9in.io/docs/reference/adapter-protocol/) for [your own user database](https://9in.io/docs/own-database/): implement `Authenticate`, `FindUser` and `OnEvent`.

## CLIs and services

`nine.NewDeviceAuth` runs the [device flow](https://9in.io/docs/devices/) (`Start`, then `Wait` until the user approves), and `nine.NewClientCredentials` gets cached [machine-to-machine](https://9in.io/docs/machine-to-machine/) tokens (`Token`, or `HTTPClient` to add them to every request):

```go
device, err := nine.NewDeviceAuth(nine.DeviceAuthConfig{Issuer: "https://acme.9in.io", ClientID: "app_…"})
code, err := device.Start(ctx)
fmt.Printf("Open %s and enter %s\n", code.VerificationURI, code.UserCode)
tokens, err := device.Wait(ctx, code)
```

## Good to know

- Every failure is a `*nine.Error` with a `Code` and `Status`; test it with `errors.Is(err, nine.ErrInvalidToken)` and friends.
- Issuers must be `https://` (http only for localhost, or with `AllowInsecureIssuer`).
- Create clients once and share them: they cache keys and tokens and are safe for concurrent use.
- Full reference and runnable examples: [pkg.go.dev/github.com/9in-io/go-sdk](https://pkg.go.dev/github.com/9in-io/go-sdk). Any OpenID Connect library, such as `github.com/coreos/go-oidc`, works too.
