Client SDK

The client/ package provides a Go SDK for CLI tools and programmatic clients consuming oneauth-protected APIs. It handles login, token storage,...

Client SDK

The client/ package provides a Go SDK for CLI tools and programmatic clients consuming oneauth-protected APIs. It handles login, token storage, automatic token refresh, and authenticated HTTP requests.

Want to skip the SDK and just grab a token? See cmd/oneauth/ — a Cobra CLI wrapping the same SDK. oneauth token {browser,client-credentials,password,refresh} <issuer> --client-id … prints a JSON / bash / bare-token shape suitable for shell scripts and CI.

Architecture

flowchart TD
    AC["AuthClient<br/>- Login / Logout<br/>- GetToken() with automatic refresh<br/>- HTTPClient() returns authenticated *http.Client"]
    CS["CredentialStore<br/>(interface)"]
    RT["refreshTransport<br/>(401 retry +<br/>pre-expiry refresh)"]
    AT["AuthTransport<br/>(static Bearer header)"]
    FS["client/stores/fs<br/>JSON file<br/>~/.config/&lt;app&gt;"]

    AC --> CS
    AC --> RT
    AC --> AT
    CS --> FS

Quick Start

import (
    "github.com/panyam/oneauth/client"
    "github.com/panyam/oneauth/client/stores/fs"
)

// 1. Create a credential store
store, err := fs.NewFSCredentialStore("", "myapp")
// Stores credentials at ~/.config/myapp/credentials.json

// 2. Create an auth client
authClient := client.NewAuthClient("https://api.example.com", store)

// 3. Login
cred, err := authClient.Login("user@example.com", "password", "read write")

// 4. Use the authenticated HTTP client
resp, err := authClient.HTTPClient().Get("https://api.example.com/resource")
// Authorization: Bearer <token> is added automatically
// On 401, token is refreshed and request retried

AuthClient

The main entry point for the client SDK.

Constructor

func NewAuthClient(serverURL string, store CredentialStore, opts ...ClientOption) *AuthClient

The server URL is normalized to scheme://host (path is stripped). Default token endpoint is /auth/cli/token. If store is nil, a no-op store is used — methods that return credentials (Login, LoginWithBrowser, ClientCredentialsToken) still work and return the credential to the caller, but tokens are not persisted between calls. This is useful for conformance testing and single-request flows (e.g., MCPKit’s OAuthTokenSource).

Options

// Custom token endpoint
client.NewAuthClient(url, store, client.WithTokenEndpoint("/oauth/token"))

// Custom HTTP client (inherits timeout, TLS settings)
client.NewAuthClient(url, store, client.WithHTTPClient(&http.Client{
    Timeout: 30 * time.Second,
}))

// Custom transport
client.NewAuthClient(url, store, client.WithTransport(customTransport))

// Pre-populate AS metadata for auth method negotiation (#72)
meta, _ := client.DiscoverAS("https://auth.example.com")
client.NewAuthClient(url, store, client.WithASMetadata(meta))

// Bind tokens to a proof-of-possession key (RFC 9449 DPoP)
key, _ := client.NewDPoPKey()
client.NewAuthClient(url, store, client.WithDPoPKey(key))

DPoP (RFC 9449)

With a key configured, the client mints a proof on every token request, and
the tokens that come back are bound to that key. Requests through
HTTPClient() then present the token as Authorization: DPoP <token> with a
fresh proof each time, including the ath claim that ties the proof to that
specific token.

key, err := client.NewDPoPKey()          // ES256, generated
c := client.NewAuthClient(url, store, client.WithDPoPKey(key))

// Optional: fail fast when the server does not accept our algorithm
meta, _ := client.DiscoverAS("https://auth.example.com")
if err := key.SupportedBy(meta.DPoPSigningAlgValuesSupported); err != nil {
    return err
}

cred, _ := c.ClientCredentialsToken(id, secret, []string{"read"})
resp, _ := c.HTTPClient().Get("https://api.example.com/data")  // DPoP scheme

Three things worth knowing:

  • The key must outlive the tokens. A client that discards it holds tokens
    nothing can present. NewDPoPKeyFromECDSA wraps a key loaded from storage
    for an application that persists tokens across restarts.
  • Browser login sends dpop_jkt. With a key configured,
    LoginWithBrowser adds the thumbprint to the authorization request, which
    binds the authorization code to the key (RFC 9449 §10). Per the RFC that
    adds protection over PKCE alone only when the key is unique per
    authorization request, so generate one per login if that is the goal.
  • Without a key, nothing changes. Every request stays on the bearer path.

Methods

Login

cred, err := authClient.Login("user@example.com", "password", "read write")

Sends a grant_type=password request to the token endpoint. Stores the credential and persists to disk.

Client Credentials (Machine-to-Machine)

cred, err := authClient.ClientCredentialsToken("billing-svc", "secret", []string{"billing:read"})

Sends a grant_type=client_credentials request as application/x-www-form-urlencoded (RFC 6749 §4.4.2). No refresh token — machine clients re-authenticate when the token expires. Stores the credential for subsequent API calls via HTTPClient().

Auth method negotiation (#72): If AS metadata was provided via WithASMetadata, the client sends credentials using the AS’s preferred method (client_secret_basic via Authorization header, or client_secret_post in the form body). Without metadata, defaults to client_secret_basic per RFC 6749 §2.3.1.

// With auth method negotiation
meta, _ := client.DiscoverAS("https://auth.example.com")
authClient := client.NewAuthClient(url, store, client.WithASMetadata(meta))
cred, err := authClient.ClientCredentialsToken("svc", "secret", nil)

AS Metadata Discovery (RFC 8414 / OIDC Discovery)

meta, err := client.DiscoverAS("https://auth.example.com")
// meta.TokenEndpoint, meta.JWKSURI, meta.IntrospectionEndpoint, etc.

Fetches OAuth AS metadata from well-known endpoints. Tries RFC 8414 (/.well-known/oauth-authorization-server) first, falls back to OIDC Discovery (/.well-known/openid-configuration). Supports path-based issuers (e.g., Keycloak realms).

Use WithHTTPClientForDiscovery(client) to customize the HTTP client (TLS, timeouts).

Browser Login (OAuth Authorization Code + PKCE)

cred, err := authClient.LoginWithBrowser(ctx, &client.BrowserLoginRequest{
    ClientID: "my-cli-app",
    Scopes:   []string{"openid", "read", "write"},
})

Opens the user’s default browser to the authorization server’s login page. After the user authenticates (password, SSO, MFA — whatever the AS supports), the browser redirects to a temporary loopback server that catches the authorization code. The code is exchanged for tokens via PKCE.

This is the same pattern used by gh auth login, gcloud auth login, and kubectl with OIDC. Endpoints are auto-discovered via DiscoverAS(), or can be set explicitly via AuthorizationEndpoint and TokenEndpoint in the config.

Headless mode (#71): For CI, conformance testing, or headless CLI environments, use FollowRedirects instead of opening a browser:

cred, err := authClient.LoginWithBrowser(ctx, &client.BrowserLoginRequest{
    ClientID:    "my-cli-app",
    OpenBrowser: client.FollowRedirects(nil),  // follows HTTP redirects
})

A 400-or-worse answer from /authorize (an unregistered redirect_uri, an unknown client) makes FollowRedirects return the AS’s error / error_description straight away, instead of LoginWithBrowser waiting out its timeout for a callback that never comes (issue 387). Both headless openers send Accept: text/html, application/json;q=0.9, so an AS that negotiates its error responses answers with JSON and the error code. oneauth’s /authorize does, and so does Keycloak, which puts its message (Invalid parameter: redirect_uri) in error rather than a registered code.

Consent pages: some demo authorization servers answer /authorize with a consent form instead of redirecting. client.ApproveConsent(httpClient) posts that form with its approve button, and refuses a form that has none, so it never submits a login page asking for a password. It’s meant for test and demo servers.

Registering the redirect first (DCR): an AS that matches redirect_uri exactly needs the client to register the string the login will send. Bind the listener yourself, register LoopbackRedirectURI(l.Addr()), and hand the listener over, so there’s no window where another process takes the port (issue 387):

l, _ := net.Listen("tcp", "127.0.0.1:0")
reg, _ := client.RegisterClient(dcrURL, client.ClientRegistrationRequest{
    RedirectURIs: []string{client.LoopbackRedirectURI(l.Addr())},
}, nil)
cred, err := authClient.LoginWithBrowser(ctx, &client.BrowserLoginRequest{
    ClientID: reg.ClientID,
    Listener: l, // closed by LoginWithBrowser on return
})

LoopbackRedirectURI always produces http://localhost:<port>/callback. When the registration uses something else (an IP literal, another path), set RedirectURI to that exact string; it must be loopback http with an explicit port matching the listener, and is checked before the browser opens.

Confidential client (#72): Set ClientSecret for confidential clients. The auth method (client_secret_basic vs client_secret_post) is negotiated from AS metadata:

cred, err := authClient.LoginWithBrowser(ctx, &client.BrowserLoginRequest{
    ClientID:     "my-app",
    ClientSecret: "app-secret",
    OpenBrowser:  client.FollowRedirects(httpClient),
})

Explicit endpoints with auth methods (#74): When the caller provides explicit endpoints (skipping discovery), set TokenEndpointAuthMethods so the client negotiates the correct auth method. This is common when the caller performs its own PRM→AS discovery (e.g., MCPKit):

cred, err := authClient.LoginWithBrowser(ctx, &client.BrowserLoginRequest{
    ClientID:                 "my-app",
    ClientSecret:             "app-secret",
    AuthorizationEndpoint:    meta.AuthorizationEndpoint,
    TokenEndpoint:            meta.TokenEndpoint,
    TokenEndpointAuthMethods: meta.TokenEndpointAuthMethods,
    OpenBrowser:              client.FollowRedirects(nil),
})

Without TokenEndpointAuthMethods, explicit endpoints default to client_secret_basic per RFC 6749 §2.3.1.

Handling login failures (issue 392): each way a login can fail has its own type, so a caller can act on the cause with errors.As / errors.Is instead of matching text. The messages are the same as before.

Failure Type What’s in it
AS refused /authorize (unknown client, unregistered redirect) *client.AuthorizeError Status, Code + Description for a JSON error, Body (the page’s visible text, up to 300 characters) for an HTML page
User declined, or the AS redirected back with ?error= *client.CallbackError Code (access_denied when the user said no), Description
Token endpoint refused the code *client.TokenError Status, Code (invalid_grant, invalid_client, …), Description
No callback before Timeout client.ErrLoginTimeout cancelling ctx returns ctx.Err() instead
OpenBrowser failed *client.BrowserOpenError wraps the opener’s error, so an *AuthorizeError from FollowRedirects / ApproveConsent is found through it
cred, err := authClient.LoginWithBrowser(ctx, req)
var ae *client.AuthorizeError
var te *client.TokenError
switch {
case errors.As(err, &ae) && ae.Code == "invalid_client",
    errors.As(err, &te) && te.Code == "invalid_client":
    // The AS has forgotten this client (e.g. a DCR registration lost on restart): register again.
case err != nil:
    return err // includes *client.CallbackError{Code: "access_denied"}: don't reopen the consent page
}

Signed authorization responses (JARM, issues 412 and 413): set ResponseMode to jwt, query.jwt or form_post.jwt and the AS signs its response. LoginWithBrowser checks the response JWT with client.VerifyAuthorizationResponse before it exchanges the code. The JWT’s signature must verify against the AS’s JWKS, its iss must be the issuer discovery found, its aud must be your client_id, and its exp must not have passed. Verification needs the issuer and jwks_uri, so with explicit endpoints pass WithASMetadata.

cred, err := authClient.LoginWithBrowser(ctx, &client.BrowserLoginRequest{
    ClientID:     "my-app",
    ResponseMode: "jwt",
})
if errors.Is(err, client.ErrUnverifiedAuthorizationResponse) {
    // Forged, replayed, expired, or a plain code from an AS that ignored the mode.
}

A user’s denial inside a verified response is still a *client.CallbackError. fragment and fragment.jwt fail before the browser opens, since a fragment never reaches the loopback server. To pick the signing algorithm, register AuthorizationSignedResponseAlg through DCR (below). The CLI flags are oneauth token browser --response-mode jwt and oneauth dcr register --authorization-signed-response-alg. See JARM.

*client.TokenError comes back from every grant, not just this one: Login, ClientCredentials, RefreshToken, JwtBearerGrant, TokenExchange, and PollDeviceToken for codes other than its four RFC 8628 polling sentinels.

Logout

err := authClient.Logout()

Removes the stored credential for this server.

GetToken

token, err := authClient.GetToken()

Returns the current access token. If the token expires within 5 minutes and a refresh token is available, it proactively refreshes before returning.

IsLoggedIn

if authClient.IsLoggedIn() {
    // Has a valid, non-expired credential
}

HTTPClient

httpClient := authClient.HTTPClient()
resp, err := httpClient.Get("https://api.example.com/resource")

Returns an *http.Client wired with refreshTransport that:

  1. Adds Authorization: Bearer <token> to every request
  2. Proactively refreshes tokens expiring within 5 minutes
  3. On 401 response: refreshes the token and retries the request once, resending the body through GetBody. A request whose body can’t be rewound gets the 401 back instead of being resent empty.

Credential Storage

ServerCredential

type ServerCredential struct {
    AccessToken  string    `json:"access_token"`
    RefreshToken string    `json:"refresh_token,omitempty"`
    TokenType    string    `json:"token_type,omitempty"`
    UserID       string    `json:"user_id,omitempty"`
    UserEmail    string    `json:"user_email,omitempty"`
    Scope        string    `json:"scope,omitempty"`
    ExpiresAt    time.Time `json:"expires_at"`
    CreatedAt    time.Time `json:"created_at"`
}

Helper methods:

  • IsExpired() bool — true if token has expired
  • IsExpiringSoon(within time.Duration) bool — true if expiring within the given duration
  • HasRefreshToken() bool — true if refresh token is present

CredentialStore Interface

type CredentialStore interface {
    GetCredential(serverURL string) (*ServerCredential, error)
    SetCredential(serverURL string, cred *ServerCredential) error
    RemoveCredential(serverURL string) error
    ListServers() ([]string, error)
    Save() error
}

FSCredentialStore

File-based implementation that persists credentials as JSON.

import "github.com/panyam/oneauth/client/stores/fs"

// Default path: ~/.config/myapp/credentials.json
store, err := fs.NewFSCredentialStore("", "myapp")

// Custom path
store, err := fs.NewFSCredentialStore("/path/to/credentials.json", "")

File format:

{
  "servers": {
    "https://api.example.com": {
      "access_token": "eyJhbGci...",
      "refresh_token": "a1b2c3...",
      "expires_at": "2026-03-15T10:45:00Z",
      "user_id": "user-123",
      "scope": "read write"
    }
  }
}

Security: credentials file is written with 0600 permissions (owner-only), directory with 0700.

Token Refresh Flow

flowchart TD
    U["User makes request via HTTPClient()"]
    RT["refreshTransport.RoundTrip()"]
    S1["GetToken() checks if token expires within 5 min"]
    S1A["If yes + has refresh token → refresh proactively"]
    S2["Adds Authorization: Bearer &lt;token&gt; header"]
    S3["Sends request"]
    S4["If 401 received + has refresh token:"]
    S4A["Refresh token, retry request once with new token"]

    U --> RT
    RT --> S1
    S1 --> S1A
    S1 --> S2
    S2 --> S3
    S3 --> S4
    S4 --> S4A

The refresh uses a grant_type=refresh_token request to the token endpoint. The base transport is used for refresh requests to avoid infinite loops.

Where it goes depends on discovery. With AS metadata (WithASMetadata, or a DiscoverAS result passed to it) the refresh posts the RFC 6749 §6 form to the discovered token_endpoint, which is what makes background refresh work against Keycloak or any RFC 8414 server. Without it, it posts JSON to oneauth’s own /auth/cli/token.

It presents the client the credential was issued to (ServerCredential.ClientID). The AS redeems a refresh token only for that client, and a confidential client has to authenticate, so give the AuthClient its secret:

c := client.NewAuthClient(serverURL, store,
    client.WithASMetadata(meta),
    client.WithClientSecret(secret), // memory only; never written to the store
)

The secret is sent the way the AS advertises (client_secret_basic first, then client_secret_post), the same choice RefreshToken makes.

Dynamic Client Registration & Management (RFC 7591 / 7592)

The client/dcr.go helpers let an application register itself at an authorization server and subsequently manage that registration without going through an admin UI.

Register

resp, err := client.RegisterClient(asMetadata.RegistrationEndpoint, client.ClientRegistrationRequest{
    ClientName:   "My Bot",
    RedirectURIs: []string{"https://bot.example/cb"},
    GrantTypes:   []string{"client_credentials"},
}, nil)
// resp.ClientID, resp.ClientSecret — the credentials
// resp.RegistrationAccessToken, resp.RegistrationClientURI — RFC 7592 management credentials

ClientRegistrationRequest carries every RFC 7591 / OIDC Registration field oneauth’s DCR endpoint reads: JWKS (raw JSON) or JWKSURI, TokenEndpointAuthSigningAlg, the logo, policy and terms URIs, SubjectType and SectorIdentifierURI, UserinfoSignedResponseAlg, the back-channel logout pair, and AuthorizationDetailsTypes. ClientRegistrationResponse echoes what the AS stored. An AS ignores metadata it doesn’t support (RFC 7591 §2), so compare the response with the request to see what took. From the CLI, oneauth dcr register --metadata client.json sends any of these fields, and explicit flags win over the file.

AuthorizationSignedResponseAlg picks the algorithm for this client’s signed (JARM) authorization responses. It must be one the AS lists in authorization_signing_alg_values_supported, and none is refused. It doesn’t turn JARM on; BrowserLoginRequest.ResponseMode does.

Read your own registration (RFC 7592 §2.1)

Once registered, the client holds two extra fields — RegistrationAccessToken and RegistrationClientURI. They are the management credentials for that specific registration.

The SDK follows the library-wide (ctx, *Request) → (*Response, error) convention so calls thread cancellation/deadlines through and stay shaped for future gRPC stubs.

got, err := client.GetRegistration(ctx, &client.GetRegistrationRequest{
    RegistrationClientURI:   resp.RegistrationClientURI,
    RegistrationAccessToken: resp.RegistrationAccessToken,
})
if errors.Is(err, client.ErrRegistrationUnauthorized) {
    // Token rejected — the AS returned 401. The token may have been rotated
    // (RFC 7592 §2.2 re-issues on PUT) or the client unregistered.
}
metadata := got.Registration // *ClientRegistrationResponse

GetRegistration returns the current registration metadata wrapped in a response struct. The metadata intentionally does not echo client_secret; clients that lose the secret rotate via PUT (below).

Update your own registration (RFC 7592 §2.2)

UpdateRegistration performs a full replacement of the registration metadata (not a PATCH-style merge — fields omitted from Metadata are cleared on the server). On success the AS rotates the registration_access_token; the new token surfaces on the response and the old one is invalid for any subsequent management call.

resp, err := client.UpdateRegistration(ctx, &client.UpdateRegistrationRequest{
    RegistrationClientURI:   regURI,
    RegistrationAccessToken: oldToken,
    ClientID:                clientID, // RFC 7592 §2.2 requires it; SDK auto-fills body
    Metadata: client.ClientRegistrationRequest{
        ClientName: "My Renamed Bot",
        Scope:      "read write admin",
        // ... other fields you want to KEEP must also be set; replacement is total
    },
})
if err != nil {
    if errors.Is(err, client.ErrRegistrationUnauthorized) {
        // Old token already rotated, or the AS unregistered the client.
    }
    return err
}
newToken := resp.Registration.RegistrationAccessToken // persist before discarding oldToken

OneAuth rejects updates that change token_endpoint_auth_method (would require re-keying); clients that need to switch auth method DELETE and re-register.

Delete your registration (RFC 7592 §2.3)

DeleteRegistration removes the registration AND invalidates the signing credentials. After it returns successfully, the client_secret (or asymmetric key) captured at registration can no longer mint access tokens.

_, err := client.DeleteRegistration(ctx, &client.DeleteRegistrationRequest{
    RegistrationClientURI:   regURI,
    RegistrationAccessToken: regToken,
})
if err != nil {
    if errors.Is(err, client.ErrRegistrationUnauthorized) {
        // Token rejected — already deleted, or never had management rights
    }
    return err
}
// 204 No Content. Empty response struct; nothing to inspect.

The response struct is intentionally empty today (the wire response is 204 No Content); it exists to keep the (ctx, *Req) → (*Resp, error) shape and gives forward-compat headroom.

AuthTransport (Static Token)

For simpler cases where you have a static token and don’t need refresh:

import "github.com/panyam/oneauth/client"

transport := client.NewAuthTransport("my-static-token")
httpClient := &http.Client{Transport: transport}

resp, err := httpClient.Get("https://api.example.com/resource")
// Authorization: Bearer my-static-token

Complete Example: CLI Tool

package main

import (
    "fmt"
    "os"

    "github.com/panyam/oneauth/client"
    "github.com/panyam/oneauth/client/stores/fs"
)

func main() {
    store, _ := fs.NewFSCredentialStore("", "mycli")
    auth := client.NewAuthClient("https://api.example.com", store)

    switch os.Args[1] {
    case "login":
        cred, err := auth.Login(os.Args[2], os.Args[3], "read write")
        if err != nil {
            fmt.Fprintf(os.Stderr, "Login failed: %v\n", err)
            os.Exit(1)
        }
        fmt.Printf("Logged in as %s\n", cred.UserEmail)

    case "whoami":
        if !auth.IsLoggedIn() {
            fmt.Println("Not logged in")
            os.Exit(1)
        }
        cred, _ := auth.GetCredential()
        fmt.Printf("User: %s (%s)\n", cred.UserID, cred.UserEmail)

    case "fetch":
        resp, err := auth.HTTPClient().Get(os.Args[2])
        if err != nil {
            fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
            os.Exit(1)
        }
        defer resp.Body.Close()
        // ... handle response

    case "logout":
        auth.Logout()
        fmt.Println("Logged out")
    }
}

Thread Safety

Both AuthClient and FSCredentialStore are protected by sync.Mutex. Safe for concurrent use from multiple goroutines.