# oauth

> The oauth package: app tokens, member connect, token storage and sign in with STX.

Source: https://docs.stxapp.io/sdks/go/reference/oauth/

> **Availability.** Available on US demo now. Live access is coming soon in the US and Ontario. See [Environments](https://docs.stxapp.io/environments/).

```go
import "github.com/stxapp/stx-go/oauth"
```

Package oauth lets an app call STX for its members and as itself.

An app acting for a member sends them through the authorization code flow with PKCE ([Client.Begin](/sdks/go/reference/oauth/#clientbegin), [Client.Complete](/sdks/go/reference/oauth/#clientcomplete)), keeps their tokens in a [TokenStore](/sdks/go/reference/oauth/#tokenstore), and calls the API through [Client.MemberClient](/sdks/go/reference/oauth/#clientmemberclient), which refreshes the rotating tokens before expiry and once on a 401. An app acting as itself uses a client credentials token ([Client.AppToken](/sdks/go/reference/oauth/#clientapptoken), [Client.AppClient](/sdks/go/reference/oauth/#clientappclient)) for the market and event catalogs, the market data channels and creating markets. [SignIn](/sdks/go/reference/oauth/#signin) is sign in with STX: OpenID Connect on the same flow, with the ID token verified.

The token sources implement stx.Auth, so they also plug into stx.New with stx.WithAuth. Errors from OAuth endpoints are \*[Error](/sdks/go/reference/oauth/#error) values that match the sentinels in this package; an exchange without OAuth answers with an error matching stx.ErrNotAvailable.

Flows, scopes, tokens and errors are described at [https://docs.stxapp.io/oauth/](https://docs.stxapp.io/oauth/).

## Constants and variables

```go
const (
	DefaultAuthorizePath  = "/oauth/authorize"
	DefaultTokenPath      = "/oauth/token"
	DefaultRevokePath     = "/oauth/revoke"
	DefaultIntrospectPath = "/oauth/introspect"
	DefaultRegisterPath   = "/oauth/register"
)
```

Default endpoint paths, relative to the exchange's base URL. Discovery supplies absolute URLs that take precedence.

```go
const (
	// ScopeProfileRead: who the member is (GET /api/v1/me).
	ScopeProfileRead = "profile.read"
	// ScopeBalanceRead: the cash balance and the balances channel.
	ScopeBalanceRead = "balance.read"
	// ScopePortfolioRead: positions, settlements and the ledgers, and their channels.
	ScopePortfolioRead = "portfolio.read"
	// ScopeOrdersRead: order and fill history, and the orders and fills channels.
	ScopeOrdersRead = "orders.read"
	// ScopeTransfersRead: deposit and withdrawal history (read only).
	ScopeTransfersRead = "transfers.read"
	// ScopeOrdersWrite: place and cancel orders, and arm cancel on disconnect.
	ScopeOrdersWrite = "orders.write"
)
```

Member scopes, granted to a member token through consent, in the exchange's canonical order. See [https://docs.stxapp.io/oauth/scopes/](https://docs.stxapp.io/oauth/scopes/). No scope moves money: there is no scope that starts, approves or cancels a transfer.

```go
const (
	// ScopeMarketData: the market catalog and the market data channels.
	ScopeMarketData = "market_data"
	// ScopeEvents: the event catalog, an event's players and the events channel.
	ScopeEvents = "events"
	// ScopeMarketsWrite: create markets (POST /api/v1/markets). Granted by STX only.
	ScopeMarketsWrite = "markets.write"
)
```

App scopes, carried by a client credentials app token (no member, no consent).

```go
const ScopeOpenID = "openid"
```

ScopeOpenID asks for an ID token, for sign in with STX.

```go
const (
	// WebSocketTokenHeader carries the access token on the WebSocket
	// handshake.
	WebSocketTokenHeader = "x-stx-oauth-token"
)
```

Header names the OAuth token travels in.

```go
var (
	// ErrAccessDenied: the member came back without connecting
	// (error=access_denied): they declined, or their STX account cannot be
	// connected. Nothing was granted.
	ErrAccessDenied = errors.New("oauth: access denied")
	// ErrAccountPending: the member's STX account is still being verified, so
	// STX issues no tokens yet. On a refresh the connection has not ended:
	// the stored tokens are kept, and the same refresh token works once the
	// member is verified. See https://docs.stxapp.io/oauth/members-being-verified/.
	ErrAccountPending = errors.New("oauth: account pending verification")
	// ErrTermsNotAccepted: the member left the STX terms page without
	// agreeing (error=terms_required on the callback). Nothing was granted. A
	// member already connected when new terms take effect gets
	// stx.ErrTermsRequired from their calls instead.
	ErrTermsNotAccepted = errors.New("oauth: terms not accepted")
	// ErrGrantRevoked: a refresh was refused with invalid_grant. The member
	// revoked the app, or a reused refresh token tripped reuse detection and
	// the whole grant was revoked. Send the member through consent again.
	ErrGrantRevoked = errors.New("oauth: grant revoked; the member must authorize again")
	// ErrInvalidState: the callback's state is unknown, used or expired.
	ErrInvalidState = errors.New("oauth: invalid state")
	// ErrNotConnected: the token store holds no tokens for the member.
	ErrNotConnected = errors.New("oauth: member not connected")
)
```

Sentinel errors. An \*[Error](/sdks/go/reference/oauth/#error) matches the one that describes it, so test with [errors.Is](https://pkg.go.dev/errors#Is).

## Functions

### AppScopes

```go
func AppScopes() []string
```

AppScopes returns every app scope, in canonical order.

### CanonicalScope

```go
func CanonicalScope(scope string) string
```

CanonicalScope returns the current name for scope: older names map forward, anything else is returned unchanged.

### FormatScopes

```go
func FormatScopes(scopes []string) string
```

FormatScopes joins scopes into the space-delimited wire form.

### GenerateState

```go
func GenerateState() string
```

GenerateState returns an unguessable state value that ties an authorize redirect to its callback.

### GenerateVerifier

```go
func GenerateVerifier() string
```

GenerateVerifier returns a PKCE code verifier (RFC 7636): 32 random bytes, base64url encoded, 43 characters.

### IsAppScope

```go
func IsAppScope(scope string) bool
```

IsAppScope reports whether scope is an app scope.

### IsMemberScope

```go
func IsMemberScope(scope string) bool
```

IsMemberScope reports whether scope is a member scope.

### MemberScopes

```go
func MemberScopes() []string
```

MemberScopes returns every member scope, in canonical order.

### ParseScopes

```go
func ParseScopes(scope string) []string
```

ParseScopes splits a space-delimited scope string into canonical, de-duplicated scopes, leaving out retired ones.

### S256ChallengeFromVerifier

```go
func S256ChallengeFromVerifier(verifier string) string
```

S256ChallengeFromVerifier returns the S256 code challenge for verifier: base64url(SHA-256(verifier)). STX refuses the plain method.

### TermsURLWithReturn

```go
func TermsURLWithReturn(termsURL, returnTo string) string
```

TermsURLWithReturn returns the URL to send a member to so they can accept the current STX terms and come back to your app: termsURL (from stx.APIError.TermsURL, or Token.TermsURL after a refresh) with return\_to set. returnTo must be one of your registered redirect URIs, or on the same origin as one. See [https://docs.stxapp.io/oauth/terms-and-conditions/](https://docs.stxapp.io/oauth/terms-and-conditions/).

## AppToken

```go
type AppToken struct {
	// contains filtered or unexported fields
}
```

AppToken is a cached client credentials token that mints itself again shortly before it expires. Concurrent callers share one mint. It implements stx.Auth (with reauthentication on a 401 and WebSocket handshakes), so pass it to stx.WithAuth to call the API as the app. Get one from [Client.AppToken](/sdks/go/reference/oauth/#clientapptoken).

### AppToken.AuthHeaders

```go
func (a *AppToken) AuthHeaders(ctx context.Context, _, _ string) (http.Header, error)
```

AuthHeaders returns the Bearer header for one request.

### AppToken.Fresh

```go
func (a *AppToken) Fresh(ctx context.Context) (*Token, error)
```

Fresh drops the cached token and mints one now.

### AppToken.GrantedScope

```go
func (a *AppToken) GrantedScope() string
```

GrantedScope returns the scope granted to the current token, or "" before the first mint.

### AppToken.Invalidate

```go
func (a *AppToken) Invalidate()
```

Invalidate drops the cached token, so the next call mints one.

### AppToken.Kind

```go
func (a *AppToken) Kind() string
```

Kind returns "oauth\_app".

### AppToken.Reauthenticate

```go
func (a *AppToken) Reauthenticate(ctx context.Context) (bool, error)
```

Reauthenticate mints a new token after a 401.

### AppToken.Token

```go
func (a *AppToken) Token(ctx context.Context) (*Token, error)
```

Token returns a valid app token, minting one when there is none or it expires within a minute. A token without an expiry is kept until [AppToken.Invalidate](/sdks/go/reference/oauth/#apptokeninvalidate).

### AppToken.WebSocketHeaders

```go
func (a *AppToken) WebSocketHeaders(ctx context.Context, reconnect bool) (http.Header, error)
```

WebSocketHeaders returns the handshake header. A reconnect mints a new token rather than reuse the one from the connection that dropped.

## AuthParams

```go
type AuthParams struct {
	// Scopes to ask for; empty uses Config.Scopes.
	Scopes []string
	// State overrides the generated state.
	State string
	// Prompt is "none" for a silent reconnect, or "login" or "consent".
	Prompt string
	// RedirectURL overrides Config.RedirectURL.
	RedirectURL string
	// Connection goes straight to a sign-in provider instead of the STX
	// login page: "google", "apple" or "x".
	Connection string
	// LoginHint is the member's email, if you know it, so the provider can
	// preselect the account.
	LoginHint string
	// Extra holds further authorize parameters, sent as given.
	Extra url.Values
}
```

AuthParams are the options of one authorize redirect.

## Authorization

```go
type Authorization struct {
	// URL is where to send the member's browser.
	URL string
	// State ties the callback to this redirect. Check it on return.
	State string
	// CodeVerifier is the PKCE verifier to keep server-side for the exchange.
	CodeVerifier string
	// CodeChallenge is the S256 challenge carried in URL.
	CodeChallenge string
	// RedirectURL is the redirect URI carried in URL.
	RedirectURL string
}
```

Authorization is one prepared authorize redirect.

## AuthorizationServerMetadata

```go
type AuthorizationServerMetadata struct {
	Issuer                            string   `json:"issuer"`
	AuthorizationEndpoint             string   `json:"authorization_endpoint"`
	TokenEndpoint                     string   `json:"token_endpoint"`
	RevocationEndpoint                string   `json:"revocation_endpoint,omitempty"`
	IntrospectionEndpoint             string   `json:"introspection_endpoint,omitempty"`
	RegistrationEndpoint              string   `json:"registration_endpoint,omitempty"`
	ScopesSupported                   []string `json:"scopes_supported,omitempty"`
	ResponseTypesSupported            []string `json:"response_types_supported,omitempty"`
	GrantTypesSupported               []string `json:"grant_types_supported,omitempty"`
	CodeChallengeMethodsSupported     []string `json:"code_challenge_methods_supported,omitempty"`
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
}
```

AuthorizationServerMetadata is the exchange's RFC 8414 discovery document. The exchange builds every URL on the host the request used, so discover from the same base URL you send members to.

### DiscoverMetadata

```go
func DiscoverMetadata(ctx context.Context, baseURL string, hc *http.Client) (*AuthorizationServerMetadata, error)
```

DiscoverMetadata fetches baseURL/.well-known/oauth-authorization-server. On an exchange without OAuth it returns a \*stx.NotAvailableError (feature "oauth") that matches stx.ErrNotAvailable. hc may be nil.

## BeginParams

```go
type BeginParams struct {
	AuthParams
	// Data is carried to the callback in the pending entry.
	Data map[string]string
	// TTL is how long the sign-in may take. Default 10 minutes.
	TTL time.Duration
}
```

BeginParams are the options of [Client.Begin](/sdks/go/reference/oauth/#clientbegin).

## Callback

```go
type Callback struct {
	Code    string
	Pending *PendingAuthorization
}
```

Callback is a validated authorize callback: the code and the pending sign-in its state named (now used up).

### ReadCallback

```go
func ReadCallback(ctx context.Context, pending PendingStore, query url.Values) (*Callback, error)
```

ReadCallback validates an authorize callback's query and takes its pending sign-in. The state is checked and used up before anything else, so an error on the callback counts only for a sign-in this app started. It makes no request.

Errors are \*Error values: invalid\_request (no code or state), invalid\_state (matches [ErrInvalidState](/sdks/go/reference/oauth/#constants-and-variables)), or the callback's own error (matching [ErrAccessDenied](/sdks/go/reference/oauth/#constants-and-variables), [ErrAccountPending](/sdks/go/reference/oauth/#constants-and-variables) or [ErrTermsNotAccepted](/sdks/go/reference/oauth/#constants-and-variables)).

## Client

```go
type Client struct {
	// contains filtered or unexported fields
}
```

Client runs the OAuth flows for one app: the authorization code flow with PKCE for a member, refresh with rotation, revocation, introspection, and client credentials app tokens. It is safe for concurrent use.

See [https://docs.stxapp.io/oauth/](https://docs.stxapp.io/oauth/) for the flow and the scopes.

### Discover

```go
func Discover(ctx context.Context, cfg Config) (*Client, error)
```

Discover fetches the exchange's discovery document and returns a client that uses the endpoints it advertises. On an exchange without OAuth it returns an error matching stx.ErrNotAvailable, so an app can tell "not here yet" from a misconfiguration at start-up.

### New

```go
func New(cfg Config) (*Client, error)
```

New returns a client for cfg. It makes no request.

### Client.AppClient

```go
func (c *Client) AppClient(scopes []string, opts ...stx.Option) (*stx.Client, error)
```

AppClient returns an \*stx.Client acting as the app with a cached client credentials token for scopes: the market and event catalogs, the market data channels and, with markets.write, creating markets. No scopes asks for every app scope the client holds.

**Example**

An app token calls the API as the app itself.

```go
app, err := oauth.New(oauth.Config{
	BaseURL:      "demo.stxapp.io",
	ClientID:     "stxapp_client_9f2c41d7",
	ClientSecret: "stxapp_cs_your_secret",
})
if err != nil {
	log.Fatal(err)
}
client, err := app.AppClient([]string{oauth.ScopeEvents})
if err != nil {
	log.Fatal(err)
}
types, err := client.Markets.Types(context.Background())
if err != nil {
	log.Fatal(err)
}
fmt.Println(types[stx.RulePlayerStatLine].PartnerCreate)
```

### Client.AppToken

```go
func (c *Client) AppToken(scopes ...string) *AppToken
```

AppToken returns the cached app token for scopes. The same scopes return the same \*AppToken, so every client built from this one shares a token. No scopes asks for every app scope the client holds.

### Client.AuthorizationURL

```go
func (c *Client) AuthorizationURL(p AuthParams) (*Authorization, error)
```

AuthorizationURL creates a PKCE pair and a state, and builds the authorize URL. Keep State and CodeVerifier server-side for the callback, or use [Client.Begin](/sdks/go/reference/oauth/#clientbegin) and [Client.Complete](/sdks/go/reference/oauth/#clientcomplete), which do that for you.

### Client.BaseURL

```go
func (c *Client) BaseURL() string
```

BaseURL returns the exchange's base URL, such as "[https://demo.stxapp.io](https://demo.stxapp.io)".

### Client.Begin

```go
func (c *Client) Begin(ctx context.Context, pending PendingStore, p BeginParams) (*Authorization, error)
```

Begin starts a sign-in: it prepares the redirect, saves the verifier and Data in pending under the state, and returns the redirect. Finish with [Client.Complete](/sdks/go/reference/oauth/#clientcomplete) on the callback.

**Example**

Linking a member: Begin on your login route, Complete on the callback.

```go
app, _ := oauth.New(oauth.Config{
	BaseURL:      "demo.stxapp.io",
	ClientID:     "stxapp_client_9f2c41d7",
	ClientSecret: "stxapp_cs_your_secret",
	RedirectURL:  "https://your.app/stx/callback",
	Scopes:       []string{oauth.ScopeBalanceRead, oauth.ScopeOrdersWrite},
})
pending := &oauth.MemoryPendingStore{}
tokens := oauth.NewFileTokenStore("stx-tokens.json")

http.HandleFunc("/stx/login", func(w http.ResponseWriter, r *http.Request) {
	auth, err := app.Begin(r.Context(), pending, oauth.BeginParams{Data: map[string]string{"user": "alice"}})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	http.Redirect(w, r, auth.URL, http.StatusFound)
})
http.HandleFunc("/stx/callback", func(w http.ResponseWriter, r *http.Request) {
	_, err := app.Complete(r.Context(), pending, r.URL.Query(), oauth.RedeemOptions{
		Store:         tokens,
		MemberKeyFunc: func(data map[string]string) string { return data["user"] },
	})
	switch {
	case errors.Is(err, oauth.ErrAccessDenied):
		fmt.Fprint(w, "Not connected.")
	case errors.Is(err, oauth.ErrAccountPending):
		fmt.Fprint(w, "Your STX account is still being verified.")
	case err != nil:
		http.Error(w, err.Error(), http.StatusBadRequest)
	default:
		fmt.Fprint(w, "Connected.")
	}
})
```

### Client.ClientCredentials

```go
func (c *Client) ClientCredentials(ctx context.Context, scopes ...string) (*Token, error)
```

ClientCredentials mints an app token: the app acting as itself, with app scopes only and no refresh token. No scopes asks for every app scope the client holds. For a cached token that renews itself, use [Client.AppToken](/sdks/go/reference/oauth/#clientapptoken).

### Client.ClientID

```go
func (c *Client) ClientID() string
```

ClientID returns the app's client id.

### Client.Complete

```go
func (c *Client) Complete(ctx context.Context, pending PendingStore, query url.Values, opts RedeemOptions) (*Completed, error)
```

Complete finishes a sign-in from the callback's query: it reads the callback (see [ReadCallback](/sdks/go/reference/oauth/#readcallback)), exchanges the code with the stored PKCE verifier and, with a store, saves the tokens.

### Client.Exchange

```go
func (c *Client) Exchange(ctx context.Context, code, verifier, redirectURL string) (*Token, error)
```

Exchange trades an authorization code for tokens, proving PKCE with the verifier. redirectURL must repeat the authorize request's; empty uses Config.RedirectURL.

### Client.Host

```go
func (c *Client) Host() string
```

Host returns the exchange host, such as "demo.stxapp.io".

### Client.Introspect

```go
func (c *Client) Introspect(ctx context.Context, token string) (*Introspection, error)
```

Introspect reports whether a token is active, and its scope. Confidential clients only.

### Client.IsPublic

```go
func (c *Client) IsPublic() bool
```

IsPublic reports whether the client has no secret.

### Client.MemberClient

```go
func (c *Client) MemberClient(store TokenStore, memberKey string, sessionOpts *SessionOptions, opts ...stx.Option) (*stx.Client, error)
```

MemberClient returns an \*stx.Client acting for one connected member: every REST call carries the member's access token, refreshed before expiry and once on a 401, and WebSocket handshakes send it too. opts may add client options such as stx.WithLogger; the host and auth come from c. sessionOpts may be nil.

### Client.Metadata

```go
func (c *Client) Metadata() *AuthorizationServerMetadata
```

Metadata returns the discovery document the client was built from, or nil.

### Client.ReadCallback

```go
func (c *Client) ReadCallback(ctx context.Context, pending PendingStore, query url.Values) (*Callback, error)
```

ReadCallback is [ReadCallback](/sdks/go/reference/oauth/#readcallback) with errors naming this client's authorize endpoint.

### Client.Redeem

```go
func (c *Client) Redeem(ctx context.Context, cb *Callback, opts RedeemOptions) (*Completed, error)
```

Redeem exchanges a callback read with [ReadCallback](/sdks/go/reference/oauth/#readcallback). Use the pair when one callback URL serves several apps and the app is known only from the pending entry's Data.

### Client.Refresh

```go
func (c *Client) Refresh(ctx context.Context, refreshToken string) (*Token, error)
```

Refresh trades a refresh token for a new pair. STX rotates the refresh token, so keep the one that comes back. A refused refresh matches [ErrGrantRevoked](/sdks/go/reference/oauth/#constants-and-variables); a member still being verified matches [ErrAccountPending](/sdks/go/reference/oauth/#constants-and-variables) (keep the tokens). While the member has terms to accept the refresh succeeds with TermsRequired set.

### Client.Revoke

```go
func (c *Client) Revoke(ctx context.Context, token, hint string) error
```

Revoke revokes a token (RFC 7009). A refresh token ends the member's whole grant; an access token revokes only its pair. hint is "access\_token", "refresh\_token" or empty.

### Client.Session

```go
func (c *Client) Session(store TokenStore, memberKey string, opts *SessionOptions) *Session
```

Session returns the member session for memberKey in store. opts may be nil.

### Client.Unlink

```go
func (c *Client) Unlink(ctx context.Context, store TokenStore, memberKey string) (bool, error)
```

Unlink revokes a member's grant at STX (best effort) and deletes their tokens from store. It reports whether STX confirmed the revocation; the local tokens are deleted either way.

## ClientRegistration

```go
type ClientRegistration struct {
	ClientID         string `json:"client_id"`
	ClientIDIssuedAt int64  `json:"client_id_issued_at"`
	// ClientSecret is present for a confidential client only. It is shown
	// once and cannot be recovered.
	ClientSecret string `json:"client_secret,omitempty"`
	// ClientSecretExpiresAt is Unix seconds; 0 means never.
	ClientSecretExpiresAt   int64    `json:"client_secret_expires_at,omitempty"`
	ClientName              string   `json:"client_name"`
	RedirectURIs            []string `json:"redirect_uris"`
	Scope                   string   `json:"scope"`
	GrantTypes              []string `json:"grant_types"`
	ResponseTypes           []string `json:"response_types"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method"`
	ClientURI               string   `json:"client_uri,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty"`
	SoftwareID              string   `json:"software_id,omitempty"`
	SoftwareVersion         string   `json:"software_version,omitempty"`
}
```

ClientRegistration is the RFC 7591 answer.

### Register

```go
func Register(ctx context.Context, baseURL string, req ClientRegistrationRequest, opts *RegisterOptions) (*ClientRegistration, error)
```

Register registers an OAuth client dynamically (RFC 7591). The registration is inert until a member consents. Refusals are \*Error values (invalid\_redirect\_uri, invalid\_client\_metadata, or rate\_limited with RetryAfter). An exchange without dynamic registration answers 404, which is an \*Error with StatusCode 404; its discovery document then has no registration\_endpoint.

## ClientRegistrationRequest

```go
type ClientRegistrationRequest struct {
	ClientName   string   `json:"client_name"`
	RedirectURIs []string `json:"redirect_uris"`
	// Scope is space-delimited. Empty means the exchange's default member scopes.
	Scope string `json:"scope,omitempty"`
	// TokenEndpointAuthMethod is "client_secret_basic" (the default; a
	// one-time secret is returned) or "none" (a public client, PKCE only).
	TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
	// GrantTypes is a subset of authorization_code, refresh_token and
	// client_credentials. Default authorization_code and refresh_token.
	GrantTypes      []string `json:"grant_types,omitempty"`
	ResponseTypes   []string `json:"response_types,omitempty"`
	ClientURI       string   `json:"client_uri,omitempty"`
	LogoURI         string   `json:"logo_uri,omitempty"`
	SoftwareID      string   `json:"software_id,omitempty"`
	SoftwareVersion string   `json:"software_version,omitempty"`
}
```

ClientRegistrationRequest is RFC 7591 client metadata. The exchange accepts absolute https redirect URIs, or http on a loopback address.

## Completed

```go
type Completed struct {
	Token *Token
	// Scopes are the granted scopes, which may be narrower than asked.
	Scopes []string
	// Data is what was passed to Begin.
	Data map[string]string
	// MemberKey is the key the tokens were stored under, when a store was given.
	MemberKey string
}
```

Completed is a finished sign-in.

## Config

```go
type Config struct {
	// BaseURL is the exchange's host or URL, such as "demo.stxapp.io". Empty
	// falls back to the STX_HOST environment variable.
	BaseURL string
	// ClientID is your app's client id.
	ClientID string
	// ClientSecret is the secret of a confidential client, sent as HTTP Basic
	// credentials. Leave it empty for a public client: it identifies with
	// client_id in the form and PKCE is its proof. A public client cannot
	// mint app tokens.
	ClientSecret string
	// RedirectURL is the redirect URI registered with STX (matched exactly).
	// The authorization code flow needs it.
	RedirectURL string
	// Scopes are the scopes asked for when a call names none.
	Scopes []string
	// Endpoint overrides the endpoint paths.
	Endpoint Endpoint
	// Metadata is the exchange's discovery document, when you have it
	// ([Discover] sets it). With it, an invalid_scope answer for a scope the
	// exchange does not list becomes a *stx.NotAvailableError.
	Metadata *AuthorizationServerMetadata
	// HTTPClient sends the OAuth requests. Nil uses a client with a 30
	// second timeout.
	HTTPClient *http.Client
}
```

Config describes one registered app. A process serving several apps makes one [Client](/sdks/go/reference/oauth/#client) per app.

### ConfigFromEnv

```go
func ConfigFromEnv() Config
```

ConfigFromEnv returns a Config from the environment: STX\_HOST (or STX\_BASE\_URL), STX\_OAUTH\_CLIENT\_ID, STX\_OAUTH\_CLIENT\_SECRET, STX\_OAUTH\_REDIRECT\_URI and STX\_OAUTH\_SCOPE (space-delimited).

## Endpoint

```go
type Endpoint struct {
	AuthURL       string
	TokenURL      string
	RevokeURL     string
	IntrospectURL string
}
```

Endpoint holds the OAuth endpoints, as paths on the base URL or absolute URLs. An empty field takes the default path.

## Error

```go
type Error struct {
	// Code is the RFC error code, such as "invalid_grant" or "invalid_scope".
	Code string
	// Description is the error_description, when there is one.
	Description string
	// Reason is STX's narrower reason (error_reason), such as
	// "account_pending" on an invalid_grant.
	Reason string
	// StatusCode is the HTTP status, or 0 for a check made locally.
	StatusCode int
	// Endpoint is the path that answered, such as "/oauth/token".
	Endpoint string
	// RetryAfter is the wait the endpoint asked for on a 429, or zero.
	RetryAfter time.Duration
	// RequestedScope is the scope the sign-in asked for, on an invalid_scope
	// from the authorize callback.
	RequestedScope string
	// contains filtered or unexported fields
}
```

Error is an OAuth protocol error: an RFC 6749 section 5.2 answer from an OAuth endpoint, an error carried on the authorize callback, or a check this package made (invalid\_state, invalid\_id\_token). See [https://docs.stxapp.io/oauth/discovery-and-errors/](https://docs.stxapp.io/oauth/discovery-and-errors/).

### Error.Error

```go
func (e *Error) Error() string
```

Error returns "oauth: ENDPOINT STATUS CODE: description".

### Error.Is

```go
func (e *Error) Is(target error) bool
```

Is matches the sentinel errors that describe e.

## FileTokenStore

```go
type FileTokenStore struct {
	// contains filtered or unexported fields
}
```

FileTokenStore is a [TokenStore](/sdks/go/reference/oauth/#tokenstore) kept in one JSON file, written with mode 0600 and replaced atomically. It suits a command-line tool or a single server process; the tokens are not encrypted.

### NewFileTokenStore

```go
func NewFileTokenStore(path string) *FileTokenStore
```

NewFileTokenStore returns a store backed by path. The file and its directory are created on the first Set.

### FileTokenStore.Delete

```go
func (s *FileTokenStore) Delete(_ context.Context, key string) error
```

Delete forgets the member's tokens.

### FileTokenStore.Get

```go
func (s *FileTokenStore) Get(_ context.Context, key string) (*Token, error)
```

Get returns the member's tokens, or nil.

### FileTokenStore.Set

```go
func (s *FileTokenStore) Set(_ context.Context, key string, t *Token) error
```

Set stores t for the member.

## FinishedSignIn

```go
type FinishedSignIn struct {
	Token    *Token
	Identity *Identity
}
```

FinishedSignIn is a completed sign-in.

## Identity

```go
type Identity struct {
	// Subject is the member's stable id for your app. Key your user record on
	// it, not on the email.
	Subject       string
	Email         string
	EmailVerified bool
	// Claims holds every claim.
	Claims map[string]any
}
```

Identity is the member, from the verified ID token or the userinfo endpoint.

## Introspection

```go
type Introspection struct {
	Active   bool   `json:"active"`
	Scope    string `json:"scope,omitempty"`
	ClientID string `json:"client_id,omitempty"`
	// Raw holds every field of the answer.
	Raw map[string]any `json:"-"`
}
```

Introspection is an RFC 7662 answer.

## Locker

```go
type Locker interface {
	WithLock(ctx context.Context, memberKey string, fn func(ctx context.Context) error) error
}
```

Locker is an optional [TokenStore](/sdks/go/reference/oauth/#tokenstore) method. Implement it when several processes share the store, so only one refreshes a member at a time: a second, concurrent refresh with the same rotating refresh token trips reuse detection and revokes the grant. Within one process the package already refreshes each member once at a time.

## MemoryPendingStore

```go
type MemoryPendingStore struct {
	// contains filtered or unexported fields
}
```

MemoryPendingStore is an in-memory [PendingStore](/sdks/go/reference/oauth/#pendingstore) for one process. The zero value is ready to use. Expired entries are dropped.

### MemoryPendingStore.Len

```go
func (s *MemoryPendingStore) Len() int
```

Len returns the number of sign-ins in progress.

### MemoryPendingStore.Put

```go
func (s *MemoryPendingStore) Put(_ context.Context, state string, p *PendingAuthorization) error
```

Put stores p under state.

### MemoryPendingStore.Take

```go
func (s *MemoryPendingStore) Take(_ context.Context, state string) (*PendingAuthorization, error)
```

Take returns and removes the entry for state.

## MemoryTokenStore

```go
type MemoryTokenStore struct {
	// contains filtered or unexported fields
}
```

MemoryTokenStore is an in-memory [TokenStore](/sdks/go/reference/oauth/#tokenstore) for scripts, demos and tests. The zero value is ready to use.

### MemoryTokenStore.Delete

```go
func (s *MemoryTokenStore) Delete(_ context.Context, key string) error
```

Delete forgets the member's tokens.

### MemoryTokenStore.Get

```go
func (s *MemoryTokenStore) Get(_ context.Context, key string) (*Token, error)
```

Get returns a copy of the member's tokens, or nil.

### MemoryTokenStore.Set

```go
func (s *MemoryTokenStore) Set(_ context.Context, key string, t *Token) error
```

Set stores a copy of t.

## OpenIDConfiguration

```go
type OpenIDConfiguration struct {
	Issuer                           string   `json:"issuer"`
	AuthorizationEndpoint            string   `json:"authorization_endpoint"`
	TokenEndpoint                    string   `json:"token_endpoint"`
	JWKSURI                          string   `json:"jwks_uri"`
	UserinfoEndpoint                 string   `json:"userinfo_endpoint,omitempty"`
	RevocationEndpoint               string   `json:"revocation_endpoint,omitempty"`
	IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported,omitempty"`
}
```

OpenIDConfiguration is the exchange's OpenID Connect discovery document, as far as [SignIn](/sdks/go/reference/oauth/#signin) uses it.

## PendingAuthorization

```go
type PendingAuthorization struct {
	// CodeVerifier is the PKCE verifier the code exchange presents.
	CodeVerifier string `json:"code_verifier"`
	// RedirectURL was sent to the authorize endpoint; the exchange repeats it.
	RedirectURL string `json:"redirect_url"`
	// Scope is the scope asked for, space-delimited.
	Scope string `json:"scope,omitempty"`
	// Expires is when the entry stops being valid.
	Expires time.Time `json:"expires"`
	// Data is yours, carried to the callback: a user id, an app id, a return URL.
	Data map[string]string `json:"data,omitempty"`
}
```

PendingAuthorization is one sign-in in progress, kept server-side under its state between the authorize redirect and the callback.

## PendingStore

```go
type PendingStore interface {
	Put(ctx context.Context, state string, p *PendingAuthorization) error
	Take(ctx context.Context, state string) (*PendingAuthorization, error)
}
```

PendingStore keeps sign-ins in progress, keyed by state. Take returns and removes the entry in one step, so a replayed callback finds nothing; it returns (nil, nil) for an unknown or expired state. Implementations must be safe for concurrent use.

## ProtectedResourceMetadata

```go
type ProtectedResourceMetadata struct {
	Resource               string   `json:"resource"`
	AuthorizationServers   []string `json:"authorization_servers"`
	ScopesSupported        []string `json:"scopes_supported,omitempty"`
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
	ResourceName           string   `json:"resource_name,omitempty"`
}
```

ProtectedResourceMetadata is the exchange's RFC 9728 document.

### DiscoverProtectedResource

```go
func DiscoverProtectedResource(ctx context.Context, baseURL string, hc *http.Client) (*ProtectedResourceMetadata, error)
```

DiscoverProtectedResource fetches baseURL/.well-known/oauth-protected-resource. hc may be nil.

## RedeemOptions

```go
type RedeemOptions struct {
	Store TokenStore
	// MemberKey is the key to store under. MemberKeyFunc, when set, derives
	// it from the Data given to Begin instead.
	MemberKey     string
	MemberKeyFunc func(data map[string]string) string
}
```

RedeemOptions say where [Client.Complete](/sdks/go/reference/oauth/#clientcomplete) and [Client.Redeem](/sdks/go/reference/oauth/#clientredeem) keep the tokens. Leave Store nil to keep them yourself.

## RegisterOptions

```go
type RegisterOptions struct {
	// Endpoint is the registration_endpoint from discovery, or a path.
	// Default "/oauth/register".
	Endpoint   string
	HTTPClient *http.Client
}
```

RegisterOptions tune [Register](/sdks/go/reference/oauth/#register).

## SavedSignIn

```go
type SavedSignIn struct {
	State        string `json:"state"`
	CodeVerifier string `json:"code_verifier"`
	Nonce        string `json:"nonce"`
	RedirectURL  string `json:"redirect_url,omitempty"`
}
```

SavedSignIn is what to keep in your server session between [SignIn.Start](/sdks/go/reference/oauth/#signinstart) and [SignIn.Finish](/sdks/go/reference/oauth/#signinfinish). It marshals to JSON.

## Session

```go
type Session struct {
	// contains filtered or unexported fields
}
```

Session acts for one connected member, with tokens kept in a [TokenStore](/sdks/go/reference/oauth/#tokenstore). It implements stx.Auth: every request carries the member's access token, refreshed before expiry and once on a 401, with the rotated refresh token stored each time. A revoked grant deletes the stored tokens and returns an error matching [ErrGrantRevoked](/sdks/go/reference/oauth/#constants-and-variables).

Refreshes are shared per store and member across every Session of one [Client](/sdks/go/reference/oauth/#client), so concurrent requests refresh once. Across processes, give the store a [Locker](/sdks/go/reference/oauth/#locker).

### Session.AuthHeaders

```go
func (s *Session) AuthHeaders(ctx context.Context, _, _ string) (http.Header, error)
```

AuthHeaders returns the Bearer header for one request.

### Session.Kind

```go
func (s *Session) Kind() string
```

Kind returns "oauth".

### Session.MemberKey

```go
func (s *Session) MemberKey() string
```

MemberKey returns the key the member's tokens are stored under.

### Session.Reauthenticate

```go
func (s *Session) Reauthenticate(ctx context.Context) (bool, error)
```

Reauthenticate handles a 401: when another request has already replaced the token it retries with that one, otherwise it refreshes.

### Session.Scopes

```go
func (s *Session) Scopes(ctx context.Context) ([]string, error)
```

Scopes returns the granted scopes of the stored tokens.

### Session.Token

```go
func (s *Session) Token(ctx context.Context) (*Token, error)
```

Token returns the member's tokens, refreshed first when they expire within the skew. If a refresh fails for a passing reason while the access token still works, the current tokens are returned.

### Session.WebSocketHeaders

```go
func (s *Session) WebSocketHeaders(ctx context.Context, _ bool) (http.Header, error)
```

WebSocketHeaders returns the handshake header, refreshing first when the token is near expiry, so a reconnect after expiry gets a fresh one.

## SessionOptions

```go
type SessionOptions struct {
	// Skew is how long before expiry the access token is refreshed. Default
	// 30 seconds.
	Skew time.Duration
	// OnRefresh runs after every refresh, once the new tokens are stored.
	OnRefresh func(ctx context.Context, t *Token)
	// OnGrantRevoked runs once when the grant is found revoked, after the
	// stored tokens are deleted.
	OnGrantRevoked func(ctx context.Context, err error)
	// OnTermsRequired runs after a refresh that says the member has new STX
	// terms to accept (the tokens are stored and work). Send the member to
	// termsURL when they are next in your app.
	OnTermsRequired func(ctx context.Context, termsURL string)
}
```

SessionOptions tune a member [Session](/sdks/go/reference/oauth/#session).

## SignIn

```go
type SignIn struct {
	// contains filtered or unexported fields
}
```

SignIn is sign in with STX: OpenID Connect on top of the authorization code flow, giving a server who the member is and, with member scopes, their grant, in one round trip. Server-side only: the secret and the tokens never belong in a browser. It is safe for concurrent use.

See [https://docs.stxapp.io/oauth/sign-in-with-your-stx-account/](https://docs.stxapp.io/oauth/sign-in-with-your-stx-account/).

**Example**

Sign in with STX: Start on your sign-in route, Finish on the callback.

```go
signIn, err := oauth.NewSignIn(oauth.SignInConfig{
	Issuer:       "https://demo.stxapp.io",
	ClientID:     "stxapp_client_9f2c41d7",
	ClientSecret: "stxapp_cs_your_secret",
	RedirectURL:  "https://your.app/auth/stx/callback",
})
if err != nil {
	log.Fatal(err)
}
started, err := signIn.Start(context.Background(), oauth.StartParams{Connection: "google"})
if err != nil {
	log.Fatal(err)
}
// Keep started.Saved in the user's session and redirect to started.URL.
// On the callback:
//
//	done, err := signIn.Finish(ctx, r.URL.Query(), saved)
//	userID := done.Identity.Subject
fmt.Println(started.URL != "")
```

### NewSignIn

```go
func NewSignIn(cfg SignInConfig) (*SignIn, error)
```

NewSignIn returns a SignIn for cfg. It makes no request.

### SignIn.Configuration

```go
func (s *SignIn) Configuration(ctx context.Context) (*OpenIDConfiguration, error)
```

Configuration returns the discovery document, fetched once and cached. An exchange without sign in with STX returns an error matching stx.ErrNotAvailable (feature "connect").

### SignIn.Disconnect

```go
func (s *SignIn) Disconnect(ctx context.Context, t *Token) error
```

Disconnect ends the member's connection by revoking the refresh token, or the access token when there is no refresh token.

### SignIn.Finish

```go
func (s *SignIn) Finish(ctx context.Context, query url.Values, saved SavedSignIn) (*FinishedSignIn, error)
```

Finish completes a sign-in from the callback's query and the saved state: it checks the state, exchanges the code, and verifies the ID token (signature, issuer, audience, expiry, nonce). Callback errors match [ErrAccessDenied](/sdks/go/reference/oauth/#constants-and-variables), [ErrAccountPending](/sdks/go/reference/oauth/#constants-and-variables) or [ErrTermsNotAccepted](/sdks/go/reference/oauth/#constants-and-variables); a state that is not this sign-in's matches [ErrInvalidState](/sdks/go/reference/oauth/#constants-and-variables).

### SignIn.Refresh

```go
func (s *SignIn) Refresh(ctx context.Context, refreshToken string) (*Token, error)
```

Refresh trades a refresh token for a new pair. Keep the refresh token that comes back: STX rotates it.

### SignIn.Revoke

```go
func (s *SignIn) Revoke(ctx context.Context, token, hint string) error
```

Revoke revokes one token. A refresh token ends the member's connection.

### SignIn.Start

```go
func (s *SignIn) Start(ctx context.Context, p StartParams) (*StartedSignIn, error)
```

Start prepares a sign-in: PKCE, state and nonce, and the authorize URL with openid added to the scopes.

### SignIn.UserInfo

```go
func (s *SignIn) UserInfo(ctx context.Context, accessToken, expectedSubject string) (*Identity, error)
```

UserInfo reads the member's claims from the userinfo endpoint with their access token, which must carry openid. Pass the subject you stored for the member as expectedSubject and an answer about anyone else is refused; "" skips that check. A dead token, or one without openid, is an \*Error with Code "invalid\_token".

### SignIn.VerifyIDToken

```go
func (s *SignIn) VerifyIDToken(ctx context.Context, idToken, nonce string) (*Identity, error)
```

VerifyIDToken verifies an ID token from this issuer for this app (the signature against the published keys, issuer, audience, expiry and nonce) and returns its claims. [SignIn.Finish](/sdks/go/reference/oauth/#signinfinish) already does this; use it for an ID token obtained another way.

## SignInConfig

```go
type SignInConfig struct {
	// Issuer is the exchange's public URL, such as "https://demo.stxapp.io".
	// It must equal the discovery document's issuer.
	Issuer       string
	ClientID     string
	ClientSecret string
	// RedirectURL is the redirect URI registered with STX.
	RedirectURL string
	// Scopes are asked for besides openid, which is always added.
	Scopes []string
	// ClockSkew is the leeway when checking exp and iat. Default 60 seconds.
	ClockSkew  time.Duration
	HTTPClient *http.Client
}
```

SignInConfig describes one confidential app using sign in with STX.

## StartParams

```go
type StartParams struct {
	// Connection goes straight to a sign-in provider: "google", "apple" or "x".
	Connection string
	// LoginHint is the member's email, if known.
	LoginHint string
	// Scopes override SignInConfig.Scopes for this sign-in.
	Scopes []string
	// RedirectURL overrides SignInConfig.RedirectURL.
	RedirectURL string
	// Prompt is "none" for a silent reconnect, or "login" or "consent".
	Prompt string
}
```

StartParams are the options of [SignIn.Start](/sdks/go/reference/oauth/#signinstart).

## StartedSignIn

```go
type StartedSignIn struct {
	// URL is where to send the member's browser.
	URL string
	// Saved goes in your server session for Finish.
	Saved SavedSignIn
}
```

StartedSignIn is a prepared sign-in.

## StaticToken

```go
type StaticToken string
```

StaticToken is an access token used as is, with no refresh: it implements stx.Auth for a one-off script. Pass it to stx.WithAuth.

### StaticToken.AuthHeaders

```go
func (t StaticToken) AuthHeaders(context.Context, string, string) (http.Header, error)
```

AuthHeaders returns the Bearer header.

### StaticToken.Kind

```go
func (StaticToken) Kind() string
```

Kind returns "oauth".

### StaticToken.WebSocketHeaders

```go
func (t StaticToken) WebSocketHeaders(context.Context, bool) (http.Header, error)
```

WebSocketHeaders returns the handshake header.

## Token

```go
type Token struct {
	// AccessToken goes in the Authorization header as a Bearer token.
	AccessToken string `json:"access_token"`
	// TokenType is "Bearer".
	TokenType string `json:"token_type,omitempty"`
	// RefreshToken renews the access token. STX rotates it on every refresh,
	// so always keep the one that came back last. Empty on an app token.
	RefreshToken string `json:"refresh_token,omitempty"`
	// Expiry is when the access token expires, or zero when unknown.
	Expiry time.Time `json:"expiry,omitzero"`
	// Scope is the granted scope, space-delimited. It may be narrower than
	// the scope asked for.
	Scope string `json:"scope,omitempty"`
	// IDToken is the OpenID Connect ID token, when openid was granted.
	// [SignIn.Finish] verifies it; do not trust it otherwise.
	IDToken string `json:"id_token,omitempty"`
	// TermsRequired is true when a refresh said the member has not accepted
	// the current STX terms. The tokens work, but orders are refused until
	// the member accepts at TermsURL. See [TermsURLWithReturn].
	TermsRequired bool `json:"terms_required,omitempty"`
	// TermsURL is the STX page where the member accepts the terms.
	TermsURL string `json:"terms_url,omitempty"`
}
```

Token is an OAuth token set: the answer of the token endpoint, and what a [TokenStore](/sdks/go/reference/oauth/#tokenstore) keeps for a member. It marshals to JSON for storage.

### Token.Scopes

```go
func (t *Token) Scopes() []string
```

Scopes returns the granted scopes, canonical names.

### Token.Valid

```go
func (t *Token) Valid() bool
```

Valid reports whether t has an access token that has not expired.

## TokenSource

```go
type TokenSource interface {
	Token(ctx context.Context) (*Token, error)
}
```

TokenSource supplies a valid access token. [\*AppToken](/sdks/go/reference/oauth/#apptoken) and [\*Session](/sdks/go/reference/oauth/#session) implement it.

## TokenStore

```go
type TokenStore interface {
	Get(ctx context.Context, memberKey string) (*Token, error)
	Set(ctx context.Context, memberKey string, t *Token) error
	Delete(ctx context.Context, memberKey string) error
}
```

TokenStore keeps members' tokens, keyed by any stable string you use for a member (your user id, for example). Get returns (nil, nil) when it holds nothing for the key. Implement it over your own database and encrypt the tokens at rest; [MemoryTokenStore](/sdks/go/reference/oauth/#memorytokenstore) and [FileTokenStore](/sdks/go/reference/oauth/#filetokenstore) suit one process.

Implementations must be safe for concurrent use.
