rp

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: BSD-3-Clause Imports: 22 Imported by: 2 modules, 2 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.

README

rp

Log people in with OpenID Connect from Go. This is the relying-party half: discovery, the authorization code with PKCE, the ID token checked against the login it answers, a loopback login for native applications (RFC 8252), and refresh for one resource at a time (RFC 8707). Pure Go, CGO_ENABLED=0.

go-authn/oidc is the other half, the resource-server one: it verifies a token that arrives, and gets nobody one. It is kept small on purpose, so the half that logs people in lives here.

p, err := rp.Discover(ctx, nil, "https://login.example.org")
c, err := rp.NewClient(ctx, p, rp.Config{ClientID: "portal", Secret: secret,
	RedirectURI: "https://files.example.org/callback", Scopes: []string{"openid", "offline_access"}})

f := rp.NewFlow()                         // keep it where only this browser brings it back
http.Redirect(w, r, c.AuthCodeURL(f, nil), http.StatusFound)
// at the redirect URI, once state is checked:
tok, id, err := c.Exchange(ctx, code, f)  // the ID token verified, with this login's nonce

// a token for one server; the refresh token keeps the whole grant
at, err := c.Refresh(ctx, tok.RefreshToken, rp.For{Resource: "https://fs-paris.example.org/"})

A native application logs in through the system browser:

c, tok, id, err := rp.Loopback(ctx, p, rp.Config{ClientID: "console"}, rp.OpenBrowser, nil)

What it always does

PKCE with S256 for every client, confidential ones too (RFC 9700 §2.1.1). A provider whose discovery document lists its PKCE methods without S256 is refused: it would ignore the challenge.
state and nonce 32 random bytes each per login. The ID token must carry the login's nonce, and with several audiences its azp must be this client (OIDC Core §3.1.3.7).
discovery the document must name the issuer it was fetched for, exactly (OIDC Discovery §4.3); every endpoint must be https or loopback, and so must the URL the document finally came from (a redirect into http is refused); an end-session endpoint in the clear is dropped.
ID-token keys fetched once at NewClient, and again for an unknown kid at most once per Config.MinRefresh (default one minute, go-authn/oidc's bound). A provider that rotates keys often needs a shorter MinRefresh, or a login right after a rotation is refused. The trade-off: a stream of forged kids can make the client ask the provider once per MinRefresh.
client authentication client_secret_basic, both parts form-encoded first (RFC 6749 §2.3.1). With no secret the client is public and names itself in the body (§3.2.1), as a native app must.
no redirect at the token endpoint (since v0.1.1) a 3xx is an error, not followed. On a 307 or 308 Go's client sends the body again -- the refresh token, or the code and its verifier -- wherever it points, and Basic credentials with it to the same host on any scheme or port. The caller's http.Client is not changed.
refresh resource and/or scope say what the token is for. IsInvalidGrant tells a grant that has ended from a refusal that has not (invalid_target).
revocation (since v0.4.0) c.Revoke(ctx, refreshToken, rp.RefreshTokenHint) asks the provider's revocation_endpoint (RFC 7009) to end a token, so that a copy of a logged-out session's refresh token is worth nothing; the client authenticates as at the token endpoint and a redirect is not followed. A provider with no such endpoint (or one in the clear) gives rp.ErrNoRevocation; Provider.RevocationURL says which.

Several providers (v0.3.0)

A service that logs people in at several providers (one per institution) is open to mix-up attacks (RFC 9700 §4.4). rp.NewSet() holds one Client per provider by name (Add); NewFlow(name) records the provider in Flow.Provider; AuthCodeURL(flow, extra) goes to that provider; and Exchange(ctx, name, code, flow, query) at the callback of provider name refuses, before any request leaves, a flow started at another provider and a response whose iss parameter is not that provider's issuer (RFC 9207 §2.4), then verifies the ID token against that provider's issuer and the login's nonce. Register one redirect URI per provider (RFC 9700 §4.4.2.2) and hand each callback its provider's name. Two providers with one issuer, or a name twice, are refused.

Client.CheckIssuer(query) is the RFC 9207 check on its own, for a service with a single provider: the iss parameter, when present, must be the provider's issuer and present once; one that is absent is refused when the provider's metadata says it sends it (authorization_response_iss_parameter_supported, Provider.IssParamSupported) and accepted otherwise, as the RFC allows.

The loopback login (RFC 8252)

  • It listens on 127.0.0.1, or [::1] when there is no IPv4 loopback, on a port the system picks (§7.3). It never listens on localhost (§8.3) or on any other interface.
  • It opens the system browser, never a web view (§8.12), and redirects to http://127.0.0.1:<port>/callback. The provider must accept any port for a loopback redirect; go-authn/bridge does.
  • A request on that port whose state is not this login's gets a 400 and is ignored: any local process can reach the port, so only the provider's answer ends the wait. An answer naming another issuer (RFC 9207), several, or none when the provider advertises authorization_response_iss_parameter_supported (the same CheckIssuer rule as the web flow), or carrying an error, ends it with that error.
  • The client is public: a secret shipped inside an application is no secret (§8.5). Its refresh tokens rotate (RFC 9700 §4.14.2), so refresh with one of them at a time.

Tests

go test -race ./...

The tests run against an in-process OpenID provider that is as strict as a real one:

  • exact redirect URIs, or any loopback port for a public client;
  • S256 only;
  • client_secret_basic for a confidential client, client_id in the body for a public one;
  • rotating refresh tokens with reuse detection;
  • resource becomes the only audience.

The loopback login is driven like a browser would: the authorization URL, the provider's redirect to the listener, and a local process knocking with another state first.

Each check was removed in turn, and a test failed each time:

  • state;
  • iss;
  • listening on loopback only;
  • nonce;
  • azp;
  • the issuer match at discovery;
  • S256 at discovery;
  • a public client's client_id;
  • an S256 rather than a plain challenge.

Removing the empty-ID-token check changes nothing, because go-authn/oidc refuses an empty token anyway; that check stays for its message.

Testing your own relying party: rptest

github.com/go-authn/rp/rptest is a fake OpenID provider for the tests of an application built on rp: discovery, the key set, and an authorization-code flow with PKCE S256, served over HTTPS on a loopback address.

p := rptest.New(t)
p.Redirect = "https://app.example/callback"
prov, err := rp.Discover(ctx, p.Client(), p.Issuer)
// ... then break it on purpose:
p.BadNonce = true // or BadSig, WrongAudience, Expired, WrongIssuer, Alg = "none" | "HS256", ...

Its own test runs rp's client against every fault and checks that each is refused and the good case accepted, so the fake cannot drift from rp's validator.

Licence

BSD 3-Clause.

Documentation

Overview

Package rp logs people in with OpenID Connect: it is the relying-party half that go-authn/oidc deliberately leaves out.

p, err := rp.Discover(ctx, http.DefaultClient, "https://login.example.org")
c, err := rp.NewClient(ctx, p, rp.Config{ClientID: "console", RedirectURI: redirect})
f := rp.NewFlow()
http.Redirect(w, r, c.AuthCodeURL(f, nil), http.StatusFound)
// ... at the redirect URI, with the flow found again:
tok, id, err := c.Exchange(ctx, code, f)
// ... later, a token for one resource server (RFC 8707 §2.2):
at, err := c.Refresh(ctx, tok.RefreshToken, rp.For{Resource: "https://fs-a.example.org/"})

What it always does, because each is a defence somebody once skipped:

  • PKCE with S256 (RFC 7636), for confidential clients too (RFC 9700 §2.1.1), and a provider that publishes its methods without S256 is refused at discovery: it would ignore the challenge.
  • A state and a nonce per login. The ID token is verified -- signature, issuer, audience, times, by go-authn/oidc -- and must carry this login's nonce; with several audiences, azp must be this client.
  • The discovery document must name the issuer it was fetched for, exactly (OIDC Discovery §4.3), and every endpoint must be https or loopback.

A native application uses Loopback, which runs the whole login through the system browser and a listener on 127.0.0.1 (RFC 8252). Such a client is public: a secret shipped inside an application is no secret (RFC 8252 §8.5).

Index

Constants

View Source
const (
	RefreshTokenHint = "refresh_token"
	AccessTokenHint  = "access_token"
)

RefreshTokenHint and AccessTokenHint are the token_type_hint values of RFC 7009 §2.1.

Variables

View Source
var ErrMixUp = errors.New("rp: the authorization response is not from the provider this login was sent to")

ErrMixUp is a redirect delivered to the callback of a provider other than the one the login was sent to, or carrying another provider's issuer.

View Source
var ErrNoRevocation = errors.New("rp: the provider has no revocation endpoint")

ErrNoRevocation: the provider publishes no revocation_endpoint (or one in the clear), so a token cannot be revoked at it.

View Source
var ErrUnknownProvider = errors.New("rp: unknown provider")

ErrUnknownProvider is a name that is not in the set.

Functions

func Challenge

func Challenge(verifier string) string

Challenge is the S256 code challenge of verifier (RFC 7636 §4.2).

func IsInvalidGrant

func IsInvalidGrant(err error) bool

IsInvalidGrant says whether err is the provider ending the grant.

func Loopback

func Loopback(ctx context.Context, p *Provider, cfg Config, open func(string) error, extra url.Values) (*Client, *Token, *oidc.Token, error)

Loopback logs a person in from a native application, as RFC 8252 says to:

  • it listens on the loopback IP literal, 127.0.0.1, or [::1] when there is no IPv4 loopback, on a port the system picks (§7.3); never on "localhost" (§8.3), and on no other interface;
  • it opens a single-use link on its own listener, which redirects to the authorization URL, in the system browser with open (so the state, nonce and challenge never appear in a process's arguments) -- never a web view inside the application (§8.12) -- and PKCE protects the code on its way back (§6);
  • it waits for the redirect at http://127.0.0.1:<port>/callback until ctx ends. A request whose state is not this login's is answered 400 and ignored -- any local process can reach the port -- so only the provider's answer ends the wait.

cfg.RedirectURI is set here; leave it empty. A native app is a public client (cfg.Secret empty, §8.5); go-authn/bridge accepts any loopback port for a client registered with http://127.0.0.1/callback. extra adds authorization parameters, such as RFC 8707 resources.

It returns the client (to refresh with), the tokens, and the verified ID token.

func OpenBrowser

func OpenBrowser(u string) error

OpenBrowser opens u in the system's default browser.

Types

type Client

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

Client logs people in at one provider.

func NewClient

func NewClient(ctx context.Context, p *Provider, cfg Config) (*Client, error)

NewClient is a client of p. It reads the provider's keys now, to verify ID tokens with.

func (*Client) AuthCodeURL

func (c *Client) AuthCodeURL(f Flow, extra url.Values) string

AuthCodeURL is where to send the browser. extra adds parameters, such as RFC 8707 resource indicators or a prompt.

func (*Client) CheckIssuer added in v0.3.0

func (c *Client) CheckIssuer(q url.Values) error

CheckIssuer verifies the "iss" authorization-response parameter of the redirect's query against this client's provider (RFC 9207 §2.4): when it is present it must be exactly the provider's issuer, and present once. A response without one is refused when the provider's metadata says it sends it (Provider.IssParamSupported); otherwise it is accepted, as the RFC allows and the ID token's "iss" is still verified. Use it in any redirect handler, whether or not there are several providers.

func (*Client) EndSessionURL

func (c *Client) EndSessionURL(postLogout string) string

EndSessionURL is where to send a browser to end the session at the provider too (OIDC RP-Initiated Logout §2), or "" when it has no such endpoint.

func (*Client) Exchange

func (c *Client) Exchange(ctx context.Context, code string, f Flow) (*Token, *oidc.Token, error)

Exchange trades the code the redirect brought for tokens, and verifies the ID token against the flow's nonce.

func (*Client) Provider

func (c *Client) Provider() *Provider

Provider is the provider this client logs in at.

func (*Client) Refresh

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

Refresh buys an access token with a refresh token. A provider that rotates refresh tokens returns a new one, and revokes the whole grant when a retired one comes back (RFC 9700 §4.14.2): keep the new one, and never refresh twice at once with the same.

func (*Client) Revoke added in v0.4.0

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

Revoke asks the provider to revoke a token (RFC 7009 §2): the refresh token of a login that ends, so that a copy of it is worth nothing. hint is RefreshTokenHint, AccessTokenHint or "". The provider answers 200 whether or not the token was valid (§2.2), so success says the token is not usable, not that it ever was. A 503 (§2.2.1: try later) and the provider's own errors come back as errors; with no endpoint, ErrNoRevocation. The client authenticates as it does at the token endpoint, and a redirect is not followed.

func (*Client) VerifyID

func (c *Client) VerifyID(ctx context.Context, raw, nonce string) (*oidc.Token, error)

VerifyID checks an ID token: signature, issuer, audience (this client), times -- go-authn/oidc -- and the nonce of the login it answers, so that an ID token from another login cannot be played into this one (OIDC Core §3.1.3.7). With several audiences, azp must be this client.

type Config

type Config struct {
	ClientID string
	// Secret is a confidential client's, sent with client_secret_basic
	// (RFC 6749 §2.3.1). Empty is a PUBLIC client: its client_id goes in the
	// token request instead, as a native app's must (RFC 8252 §8.5).
	Secret      string
	RedirectURI string
	// Scopes asked for at the login. Default openid. A refresh token usually
	// needs offline_access, or the provider's equivalent.
	Scopes []string
	// MinRefresh is how long the ID-token key set waits before it is fetched
	// again for an unknown kid (go-authn/oidc Config.MinRefresh; 0 is its
	// default, one minute). Lower picks up a provider's key rotation sooner;
	// it is also how often a stream of forged kids can make this client ask
	// the provider.
	MinRefresh time.Duration
}

Config is a client of a provider.

type Error

type Error struct {
	Code        string `json:"error"`
	Description string `json:"error_description"`
}

Error is the provider's refusal (RFC 6749 §5.2). invalid_grant means the grant is over and the person has to log in again; invalid_target, that a resource was refused (RFC 8707 §2).

func (*Error) Error

func (e *Error) Error() string

type Flow

type Flow struct {
	State, Nonce, Verifier string
	// Provider names the provider of a [Set] this login was sent to; [Set]
	// refuses to finish it anywhere else (RFC 9700 §4.4.2). Empty for a login
	// that does not go through a Set.
	Provider string
}

A Flow is one login in progress: what the redirect must be checked against and the code exchanged with. Keep it where only this browser can bring it back -- a sealed cookie, or the memory of the native app that started it.

func NewFlow

func NewFlow() Flow

NewFlow is a login with a fresh state, nonce and PKCE verifier: 32 bytes each from the system's generator (RFC 7636 §4.1: 43 characters, 256 bits).

type For

type For struct {
	Resource string
	Scope    string
}

For names what a refreshed token is for: a resource server (RFC 8707 §2.2: the token is for that one, the refresh token keeps the whole grant), and/or a scope, for a provider that sets the audience from a scope.

type Provider

type Provider struct {
	Issuer        string
	AuthURL       string
	TokenURL      string
	EndSessionURL string // "" when the provider has none, or one in the clear
	// RevocationURL is the RFC 7009 revocation endpoint, "" when the provider has
	// none, or one in the clear (see [Client.Revoke]).
	RevocationURL string
	// IssParamSupported: the provider says it sends its issuer in every
	// authorization response (RFC 9207 §3), so a response without one is refused.
	IssParamSupported bool
	// contains filtered or unexported fields
}

Provider is what discovery says about an OpenID provider.

func Discover

func Discover(ctx context.Context, hc *http.Client, issuer string) (*Provider, error)

Discover reads issuer's /.well-known/openid-configuration.

type Set added in v0.3.0

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

A Set is the providers a service logs people in at, by name.

func NewSet added in v0.3.0

func NewSet() *Set

NewSet is an empty set.

func (*Set) Add added in v0.3.0

func (s *Set) Add(name string, c *Client) error

Add registers a client under name. Two names for one issuer, or one name twice, are refused: a login would not say which provider it is for.

func (*Set) AuthCodeURL added in v0.3.0

func (s *Set) AuthCodeURL(f Flow, extra url.Values) (string, error)

AuthCodeURL is where to send the browser for the flow's provider.

func (*Set) Client added in v0.3.0

func (s *Set) Client(name string) *Client

Client is the provider's client, or nil.

func (*Set) Exchange added in v0.3.0

func (s *Set) Exchange(ctx context.Context, name, code string, f Flow, query url.Values) (*Token, *oidc.Token, error)

Exchange finishes a login at the callback of provider name. query is the redirect's query (for its "iss"). It refuses, before any request leaves, a flow that was started at another provider and a response whose iss is not this provider's; then it is Client.Exchange at that provider, whose ID token is verified against that provider's issuer and this login's nonce.

func (*Set) Names added in v0.3.0

func (s *Set) Names() []string

Names are the providers, in the order they were added.

func (*Set) NewFlow added in v0.3.0

func (s *Set) NewFlow(name string) (Flow, error)

NewFlow is a login at provider name: NewFlow with the provider recorded. Keep the Flow where only this browser can bring it back, as for a single provider.

type Token

type Token struct {
	AccessToken  string
	RefreshToken string // "" when none was issued, or the old one stays good
	IDToken      string
	Expiry       time.Time
}

Token is a token endpoint's answer (RFC 6749 §5.1, OIDC Core §3.1.3.3).

Directories

Path Synopsis
Package rptest is a fake OpenID provider for the tests of a relying party built on go-authn/rp.
Package rptest is a fake OpenID provider for the tests of a relying party built on go-authn/rp.

Jump to

Keyboard shortcuts

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