httpclient

package
v0.0.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 24 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package httpclient is a general OAuth client, with go-client, which signs in to a resource which needs to be authorized, such as an MCP server's, or go-auth's own APIs:

  • A request which isn't authorized returns an AuthError, with the server's challenge.
  • How a token is got is discovered: the resource's metadata (RFC 9728), and that of its authorization servers (RFC 8414, or OpenID Connect).
  • A client is registered (RFC 7591), or one is given.
  • Authorize, and Exchange, are the authorization code grant, with PKCE's S256, and a resource indicator (RFC 8707), and TokenSource refreshes the grant's token.
  • Login does it all, for a command, with a loopback callback (RFC 8252), at a URL a browser opens.

Index

Constants

View Source
const (
	ResourceMetadataPath = ".well-known/oauth-protected-resource"
	OAuthMetadataPath    = ".well-known/oauth-authorization-server"
	OIDCMetadataPath     = ".well-known/openid-configuration"
)

The well-known paths of a resource's metadata, and of an authorization server's, as OAuth, and OpenID Connect, have them

View Source
const AuthenticateHeader = "WWW-Authenticate"

AuthenticateHeader is the header of a server's challenges

View Source
const CallbackPath = "/callback"

CallbackPath is the path of a loopback's callback

Variables

View Source
var ErrNoMetadata = errors.New("no metadata")

ErrNoMetadata is wrapped by discovery's ErrNotFound when each of the authorization servers' well-known URLs was missing (404 or 405), rather than failed, or wasn't metadata, so the server isn't an authorization server, rather than one which couldn't be discovered

Functions

This section is empty.

Types

type AuthError

type AuthError struct {
	Scheme string     `json:"scheme"`
	Params url.Values `json:"params,omitempty"`
}

AuthError is a server's challenge, as a request to it isn't authorized: its scheme, such as Bearer, and its parameters, by their names in lower case, such as realm, and resource_metadata, the URL of the resource's metadata

func AsAuthError

func AsAuthError(err error) *AuthError

AsAuthError returns the AuthError the error is, or wraps, or nil

func ParseChallenge added in v0.0.15

func ParseChallenge(header http.Header) *AuthError

ParseChallenge returns the challenge of the header, of its challenges, which is the Bearer one, when it has one, as that's the scheme a token is for, or otherwise its first, or nil, when it hasn't any

func (*AuthError) Error

func (e *AuthError) Error() string

Error returns the challenge's error, and its description, when it has them, or that it isn't authorized

func (*AuthError) Get added in v0.0.15

func (e *AuthError) Get(key string) string

Get returns the value of the challenge's parameter, whatever the case of its name, or nothing

type Authorization added in v0.0.15

type Authorization struct {
	Grant
	URL      string `json:"url"`
	State    string `json:"-"`
	Verifier string `json:"-"`
}

Authorization is an authorization which is waited for: the URL a person authorizes it at, its state, which its callback is matched with, and its PKCE verifier, which its code is exchanged with

type Client

type Client struct {
	*client.Client
	// contains filtered or unexported fields
}

Client is a client of a resource, at its endpoint, with go-client, whose requests which aren't authorized return an AuthError, and which discovers how a token for the resource is got

func New

func New(endpoint string, opts ...client.ClientOpt) (*Client, error)

New returns a client of the resource at the endpoint, with go-client's options, such as a token, which the endpoint is applied after, so an option can't change it

func NewWithDiscovery added in v0.0.16

func NewWithDiscovery(endpoint string, opts []client.ClientOpt, discovery ...client.ClientOpt) (*Client, error)

NewWithDiscovery returns a client of the resource at the endpoint, as New does, with the options of its requests, and of those which discover how it's authorized, register a client, and get a token, which can be to another origin, such as a trace, a tracer, or a timeout, which mustn't be credentials, such as the resource's token

func (*Client) Authorize added in v0.0.15

func (c *Client) Authorize(metadata *Metadata, client Registration, redirectURI string, scopes ...string) (*Authorization, error)

Authorize starts the authorization of the resource, whose metadata is discovered, by its first authorization server, which needs to support PKCE's S256, for the client, which is registered, with the redirect URI, and the scopes, or else those the resource says it supports, and returns the URL a person authorizes it at. Returns ErrNotImplemented when the server doesn't support S256, and ErrBadParameter when the redirect URI isn't an http, or https, URL.

func (*Client) Discover

func (c *Client) Discover(ctx context.Context, resource string) (*Metadata, error)

Discover returns how a token for the resource at the URL, or the client's endpoint, when it's empty, is got: its metadata, at its well-known path, with its path, or without, and that of its authorization servers, or of its origin, as an authorization server, when it says none. Returns ErrNotFound when no authorization server's metadata is found.

func (*Client) DiscoverResource added in v0.0.15

func (c *Client) DiscoverResource(ctx context.Context, err error) (*ResourceMetadata, error)

DiscoverResource returns the metadata of the resource, alone, without that of its authorization servers, such as for its name: from the URL of its metadata the error has, when it's an AuthError which has one, or otherwise at its well-known path, of the client's endpoint, with its path, or without. Returns ErrNotFound when it has none.

func (*Client) DiscoverWithError

func (c *Client) DiscoverWithError(ctx context.Context, err error) (*Metadata, error)

DiscoverWithError returns how a token is got, as the error, which is an AuthError, says, from the URL of the resource's metadata it has, when it has one, or otherwise as Discover does, for the client's endpoint. Returns the error, when it isn't an AuthError.

func (*Client) DoAuthWithContext

func (c *Client) DoAuthWithContext(ctx context.Context, req client.Payload, v any, opts ...client.RequestOpt) error

DoAuthWithContext makes the request, as DoWithContext does, and returns an AuthError, with the server's challenge, when it isn't authorized, which is a 401 Unauthorized response with a WWW-Authenticate header, so how a token is got for it can be discovered, with DiscoverWithError

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint returns the endpoint of the resource

func (*Client) Exchange added in v0.0.15

func (c *Client) Exchange(ctx context.Context, a *Authorization, query url.Values) (*Grant, error)

Exchange completes the authorization, with its callback's query: the state, which must be the authorization's, and the code, which is exchanged, with the verifier, for a token, or the error the authorization server said. Returns the grant, with the token, or ErrBadParameter, when it wasn't authorized, or the code couldn't be exchanged.

func (*Client) Login added in v0.0.15

func (c *Client) Login(ctx context.Context, err error, name string, client *Registration, open func(string) error, scopes ...string) (*Grant, error)

Login authorizes the resource, for a command: how is discovered, from the error, when it's an AuthError, which a request to it returned, or else from the resource, and a client, which is given, or else registered, with the name, is authorized, with a loopback callback, at the URL open opens, such as in a browser, and returns the grant, with its token. It waits until it's authorized, or the context is done.

func (*Client) Register added in v0.0.15

func (c *Client) Register(ctx context.Context, server ServerMetadata, name string, redirectURIs []string, scopes ...string) (*Registration, error)

Register registers a client, with the name, and the URIs it's redirected to, and the scopes, with the authorization server, which has a registration endpoint, and returns it, without the resource's credentials, as it's another's. A server which says the request isn't valid, as some don't register a client with scopes, even those they say they support, is asked again, without them, as they're optional, and asked for as it's authorized. Returns ErrNotImplemented when the server doesn't register clients, so one's identifier is needed.

func (*Client) TokenSource added in v0.0.15

func (c *Client) TokenSource(ctx context.Context, grant *Grant, fn func(*oauth2.Token)) oauth2.TokenSource

TokenSource returns a source of the grant's token, which is refreshed, with its refresh token, client and resource indicator, when it's expired, with the client's options, and fn, when it isn't nil, is called with a new token, so it's kept

type Grant added in v0.0.15

type Grant struct {
	Server      ServerMetadata `json:"server"`
	Client      Registration   `json:"client"`
	RedirectURI string         `json:"redirect_uri"`
	Resource    string         `json:"resource,omitempty"`
	Scopes      []string       `json:"scopes,omitempty"`
	Token       *oauth2.Token  `json:"token,omitempty"`
}

Grant is what a resource was authorized with: its authorization server, the client, the redirect URI, the resource and scopes, and the token, which is refreshed with them, so it's what's kept

type Loopback added in v0.0.15

type Loopback struct {
	// contains filtered or unexported fields
}

Loopback is a callback, on the loopback interface, at a port which is free, which a command's authorization redirects to, as RFC 8252 has it, so it's waited for

func NewLoopback added in v0.0.15

func NewLoopback() (*Loopback, error)

NewLoopback listens for a callback, on 127.0.0.1, until it's closed

func (*Loopback) Close added in v0.0.15

func (l *Loopback) Close() error

Close stops listening

func (*Loopback) RedirectURI added in v0.0.15

func (l *Loopback) RedirectURI() string

RedirectURI is the URI the authorization redirects to

func (*Loopback) Wait added in v0.0.15

func (l *Loopback) Wait(ctx context.Context) (url.Values, error)

Wait returns the query of the first callback, which has the code, and the state, or the error the authorization server said, or the context's error

type Metadata added in v0.0.15

type Metadata struct {
	Resource             ResourceMetadata `json:"resource,omitzero"`
	AuthorizationServers []ServerMetadata `json:"authorization_servers,omitempty"`
}

Metadata is how a token for a resource is got: the resource's metadata, when it has it, and that of its authorization servers

type Registration added in v0.0.15

type Registration struct {
	ClientID     string   `json:"client_id"`
	ClientSecret string   `json:"client_secret,omitempty"`
	RedirectURIs []string `json:"redirect_uris,omitempty"`
}

Registration is a client, as an authorization server registered it: its identifier, its secret, when it has one, and the URIs it's redirected to

type ResourceMetadata added in v0.0.15

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

ResourceMetadata is a protected resource's metadata, which says which authorization servers issue tokens for it https://datatracker.ietf.org/doc/html/rfc9728

type ServerMetadata

type ServerMetadata struct {
	Issuer                            string   `json:"issuer"`
	AuthorizationEndpoint             string   `json:"authorization_endpoint,omitempty"`
	TokenEndpoint                     string   `json:"token_endpoint,omitempty"`
	RegistrationEndpoint              string   `json:"registration_endpoint,omitempty"`
	RevocationEndpoint                string   `json:"revocation_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"`
	IssParameterSupported             bool     `json:"authorization_response_iss_parameter_supported,omitempty"`
}

ServerMetadata is an authorization server's metadata, which says where a person authorizes a client, a token is got, and a client is registered https://datatracker.ietf.org/doc/html/rfc8414

func (ServerMetadata) Config added in v0.0.15

func (server ServerMetadata) Config(registration Registration, redirectURI string, scopes ...string) *oauth2.Config

Config returns the configuration of the authorization code grant, with the server, for the client, its redirect URI, and the scopes, which its code is exchanged, and its token refreshed, with

func (ServerMetadata) SupportsS256 added in v0.0.15

func (server ServerMetadata) SupportsS256() bool

SupportsS256 returns true when the authorization server says it supports PKCE's S256, which a client needs, as MCP has it

type SignIn added in v0.0.18

type SignIn struct {
	Server     ServerMetadata `json:"server"`
	ClientID   string         `json:"client_id"`
	Scopes     []string       `json:"scopes,omitempty"`
	Credential string         `json:"credential,omitempty"`
}

SignIn is what's needed for a person to sign in, so a resource can be used: the authorization server, the client which is signed in to, the scopes which are asked for, and the key of the credential which is stored once they've signed in. It has no secrets, so a server returns it to its client, which authorizes, such as with Authorize, at a loopback address, and the server, which has the client's secret, exchanges the code.

func SignInOf added in v0.0.18

func SignInOf(err error) *SignIn

SignInOf returns what's needed to sign in, of an error which is a SignInError, or nil

type SignInError added in v0.0.18

type SignInError struct {
	SignIn
	Err error
}

SignInError is the error of a resource whose user needs to sign in, such as when they haven't, or their grant is for another client, or doesn't have the scopes the resource needs, or is revoked, with how they sign in

func NewSignInError added in v0.0.18

func NewSignInError(signIn SignIn, err error) *SignInError

NewSignInError returns the error, with how to sign in

func (*SignInError) Error added in v0.0.18

func (e *SignInError) Error() string

func (*SignInError) Unwrap added in v0.0.18

func (e *SignInError) Unwrap() error

Unwrap returns the error, so it's matched with errors.Is

type Tokens added in v0.0.15

type Tokens struct {
	// contains filtered or unexported fields
}

Tokens keeps a command's tokens, by the endpoint they're for, in a file, which only its owner can read, so a command signs in once, and its other commands send the token

func NewTokens added in v0.0.15

func NewTokens(path string) (*Tokens, error)

NewTokens returns the tokens in the file, which is made, with its directory, when a token is kept

func (*Tokens) Delete added in v0.0.15

func (t *Tokens) Delete(endpoint string) error

Delete forgets the token for the endpoint, or returns not found

func (*Tokens) Get added in v0.0.15

func (t *Tokens) Get(endpoint string) (*oauth2.Token, error)

Get returns the token for the endpoint, or not found, when there isn't one. It can have expired.

func (*Tokens) Set added in v0.0.15

func (t *Tokens) Set(endpoint string, token *oauth2.Token) error

Set keeps the token for the endpoint, replacing any, and removes those which have expired

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL