oidc

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 30 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.

README

oidc-caep-risc-go

A confidential OpenID Connect relying party for a traditional Go application, and a CAEP and RISC receiver on one Shared Signals poll stream. Authorization Code with PKCE (S256) is required. Client authentication is client_secret_basic, client_secret_post, or private_key_jwt. A public client (tokenEndpointAuthMethod "none") is refused. The library uses the Go standard library for HTTP, JSON, and RSA signatures.

JSON configuration keys match the Python library oidc-caep-risc. signals omitted or true keeps CAEP and RISC on. signals: false does not start the receiver, does not require transmitter metadata, and drops ssf.read and ssf.manage from the scope list after the default scopes are applied. DEFAULT_SCOPES still names those two scopes. The shipped demo leaves signals on (the key is omitted).

The license is MIT. Publishing is not set up.

The defaults follow one client profile, shared with the other six libraries: PKCE S256, state, nonce, RFC 9207 iss, PAR when the provider offers it, DPoP when the provider offers ES256, RS256 ID tokens, a required typ and at_hash, acr enforced when requested, and a per-session token cache. See Settings and defaults.

Usage

package main

import "github.com/rcbj/oidc-caep-risc-go"

func main() {
    rp, err := oidc.FromFile("oidc.json")
    if err != nil {
        panic(err)
    }
    request, err := rp.Authorize()
    if err != nil {
        panic(err)
    }
    // redirect the browser to request.URL; keep State, Nonce, and CodeVerifier
    who, err := rp.Complete(query, request)
    _ = who
}

Tokens stay in this process. Keep the transaction until the browser returns (State, Nonce, CodeVerifier, RedirectURI, ACRValues).

Settings and defaults

The same defaults and rules apply whether the client is loaded with FromFile / ResolveConfig or created directly with Create. Create works on a copy of the map it is given.

Key Default Meaning
par auto auto pushes the authorization request when the provider has a PAR endpoint; always fails at creation without one; never does not push. When the provider's metadata says require_pushed_authorization_requests: true, never fails at creation and auto always pushes.
dpop auto DPoP (RFC 9449). auto uses it when the provider's dpop_signing_alg_values_supported lists ES256; always fails at creation when it does not; never sends no proofs.
dpopKey none A PEM ES256 (P-256) private key (inline, file:, env:, or a path in a configuration file). Without it the client generates a key when it is created and holds it in memory only. Name one when several processes share sign-ins.
idTokenSigningAlgs ["RS256"] The ID token algorithm allow-list. Each algorithm must also be advertised by the provider (the others are dropped; none left fails at creation). none is never accepted. A symmetric algorithm (HS256...) is accepted only when it is named here.
idTokenSignedResponseAlg none One pinned algorithm; it replaces the allow-list and must be advertised.
requireIdTokenTypAndAtHash true The ID token header must carry typ JWT or application/jwt (any case), and when the token response carries an access token the ID token must carry a matching at_hash. false checks each only when present.
acrValues none A list (or a space-separated string). When set, or when AuthorizeOptions.ACRValues is given, the request carries acr_values, the transaction keeps them (Transaction.ACRValues), and the ID token from the code exchange must carry an acr that is one of them. A refresh does not re-check acr.
clockToleranceSec 30 Clock skew allowed on exp, nbf, iat and auth_time. An iat more than this in the future is refused.
maxIdTokenAgeSec 600 The oldest iat accepted.
redirectUri, postLogoutRedirectUri https, or http on a loopback host (localhost, 127.0.0.1, [::1]). allowInsecure does not relax this. AuthorizeOptions.RedirectURI is held to the same rule.
DPoP

With DPoP on, a proof (typ dpop+jwt, the public key as jwk, jti, htm, htu without query or fragment, iat) goes on every request to the PAR endpoint and the token endpoint (code, refresh and client-credentials grants), and dpop_jkt goes on the authorization request (in the PAR body when PAR is used). The token response's token_type must then be DPoP (any case); without a proof it must be Bearer. A mismatch is refused.

UserInfo, ResourceRequest(method, url, accessToken, tokenType, headers, body) and every call the Shared Signals receiver makes to the transmitter (with ReceiverOptions.Client) send a DPoP-bound token as Authorization: DPoP <token> with a proof carrying ath. A 400 use_dpop_nonce from the authorization server, or a 401 with WWW-Authenticate: DPoP error="use_dpop_nonce" from a resource server, is retried once with the DPoP-Nonce the response gave; the latest nonce is kept per server origin and sent on the next proof. DPoPEnabled() and DPoPThumbprint() report the state.

The session token cache
login, err := rp.CompleteSession(query, request, sessionID) // "" makes a handle: login.Session
access, err := rp.SessionAccessToken(sessionID)             // Access{AccessToken, TokenType, ...}
err = rp.RemoveSession(sessionID)                           // sign-out

CompleteSession is Complete that also keeps the sign-in's tokens under a session identifier the application chooses. SessionAccessToken returns the cached access token while it has more than 30 seconds left; otherwise it refreshes (with a DPoP proof when DPoP is on), stores the new tokens and returns them. A failed refresh removes the entry and returns an OidcError with Code session. RemoveSession clears an entry; a receiver created with ReceiverOptions{Client: rp} clears the entry of every session an event ends (a CAEP session-revoked). The default store is MemorySessionStore; rp.SetSessionStore(store) replaces it with any SessionStore (Get, Set, Delete), for example one shared across processes.

The Shared Signals receiver

ReceiverOptions{Client: rp, Scope: "ssf.manage"} makes every transmitter call with rp's client-credentials token for that scope, as a DPoP-bound token with proofs when DPoP is on. Headers still works when Client is nil.

Tests

docker build --target test .

The suite runs in a container.

The tests build an in-process stub provider and a stub transmitter. They do not need a live iya-sts. trust_chain_test.go runs the install script and scripts/trust_chain.py against an HTTPS stub on a four-certificate chain shaped like iya-sts's, and checks the library trusts it through the saved file, verifies the host name, and refuses a forged leaf.

python3 scripts/live_iya_sts.py is the live half. It starts iya-sts when IYA_STS_URL is unset, copies this checkout to a scratch build context without demo/generated, builds the demo image from it as a fresh clone would be, runs the install script against that copy (which writes the tlsCa chain), builds the image again (which bakes the chain in), checks the image's /app/demo/generated/idp-ca.pem equals the saved chain, starts the demo with no CA mount and TLS_CA_REFRESH=0 (only the client secret is mounted), signs in, and requires a credential-change event and a session-revoked event on GET /live-status. The second event ends the local session. It never binds port 3000 or 8081. Secrets reach docker run as -e NAME, never -e NAME=value. The nightly workflow runs the unit suite and this script. .github/workflows/nightly.yml runs at 07:18 UTC (18 7 * * *) and on workflow_dispatch. IYA_STS_IMAGE starts a fresh container from an image already built; without it or IYA_STS_URL the script clones and builds iya-sts main. LIVE_STS_PORT defaults to 18559 and LIVE_DEMO_PORT to 18659; the script refuses 3000, 8081, and 18481 through 18495. Registration runs scripts/configure_iya_sts.py with the host's stdlib python3, never Go. Always use a fresh iya-sts: a second registration of the same client fails.

Layout

Path What it is
*.go The library, package oidc. Module github.com/rcbj/oidc-caep-risc-go.
*_test.go go test ports of the Python relying-party and Shared Signals tests.
demo demo/main.go. Config is demo/oidc.json. Its message pages are drawn with html/template (demo/main_test.go).
scripts/configure_iya_sts.py Registers the confidential client on iya-sts (with id_token_signed_response_alg RS256, the library's default allow-list) and writes the listener CA trust chain to the file tlsCa names. Loopback redirects follow the running container's PORT, then the shell PORT.
scripts/live_iya_sts.py The live sign-in against iya-sts, separate from the unit suite.
Dockerfile, docker-compose.yml The demo image. Compose uses host networking.

The iya-sts trust chain (tlsCa)

tlsCa in demo/oidc.json names the iya-sts TLS listener CA trust chain the library trusts. The default is generated/idp-ca.pem, relative to demo/. The value may also be file:<path>, env:<NAME>, or the PEM itself. The library adds every certificate in it to the system trust store (x509.CertPool.AppendCertsFromPEM reads every PEM block, so the whole chain works and the root alone does too), keeps Go's normal chain verification, and checks the host name against the certificate's SANs (DNS name or IP literal). There is no pin shortcut: a forged leaf sent in front of the real CA certificates is refused.

scripts/configure_iya_sts.py, the install script, writes that file on every run. It saves the whole chain iya-sts publishes at GET /tls/server-certificate (leaf, TLS Issuing CA, Intermediate, Root), or the chain from the TLS handshake when that path does not answer. It prints the path, the trust anchor's subject and its SHA-256 fingerprint. Compare the anchor with the Root CA on iya-sts's PKI page.

The demo image build copies that file into the image at /app/demo/generated/idp-ca.pem, so the image trusts that iya-sts with no bind mount and no fetch. Run the install script before you build the image. Rebuild the image after running the install script against a different iya-sts. .dockerignore admits only that file from demo/generated; the client secret and a generated test-user password stay out of the image. A build with no chain file yet (a fresh clone, CI) still succeeds; the image then has no tlsCa file.

The mechanism is COPY demo demo in the final stage, after the Go binary is built, plus .dockerignore's demo/generated/* and !demo/generated/idp-ca.pem. Do not replace it with a COPY that names the file or globs for it: when the file is absent, both BuildKit and the classic builder fail. A directory COPY of demo/ (which always exists) succeeds in both. A new chain changes only that last layer; the binary is not rebuilt.

The container entrypoint also refreshes the file from the provider at start, because a development iya-sts makes a new CA when it restarts. A failed refresh keeps the file from the build. TLS_CA_REFRESH=0 turns the refresh off. python3 scripts/trust_chain.py --config demo/oidc.json refreshes it by hand.

When the install script creates the test user and iya-sts generates its password, the password is written to demo/generated/<user>.password (created 0600), not printed; only that path is. No script prints the client secret, the path of the file that holds it, or a plan built from it: --dry-run shows <client secret>, and the client-secret file is created 0600.

Demo

PORT defaults to 3000. A loopback redirect and post-logout URL follow PORT. Any other host is left as written. An explicit PUBLIC_URL or --public-url replaces the origin and keeps the path. The default http://localhost:3000 is not an explicit public URL.

docker compose up --build

GET /healthz returns ok. GET / is the page; it asks the library's session cache for the session's access token (SessionAccessToken, refreshing it when needed) and ends the session when that is refused. GET /login starts Authorize and redirects. GET /callback completes the code exchange. POST /logout signs the local session out. GET /live-status is JSON for the sign-in and the Shared Signals events this process has accepted. It does not include tokens.

docker-compose.yml sets network_mode: host. The image sets ENV PORT=3000. The health check calls http://127.0.0.1:$PORT/healthz (it said $$PORT until 2026-11-02, which the shell expands to its process ID). The running container's PORT wins over the shell's when scripts/configure_iya_sts.py registers the application.

Demo JSON uses file: and the configuration's own placeholders. It does not contain a generated secret or key.

Documentation

Index

Constants

View Source
const DefaultScopes = "openid profile email offline_access ssf.read ssf.manage"

DefaultScopes are the scopes RelyingParty asks for unless the configuration names others.

View Source
const SessionRefreshMargin = 30.0

SessionRefreshMargin is how much life a cached access token must have left for SessionAccessToken to return it without a refresh.

Variables

View Source
var (
	CAEPEvents = eventsWithPrefix(caepPrefix)
	RISCEvents = eventsWithPrefix(riscPrefix)
)

CAEPEvents and RISCEvents follow the order the event names were defined.

View Source
var AsymmetricJWSAlgs = []string{
	"RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512", "EdDSA", "Ed25519",
}

AsymmetricJWSAlgs are the asymmetric JWS algorithms this client verifies. HMAC algorithms are accepted only when an ID token names one explicitly.

View Source
var DefaultEndingEvents = []string{
	Event["sessionRevoked"], Event["accountDisabled"], Event["accountPurged"],
	Event["credentialCompromise"], Event["sessionsRevoked"],
}

DefaultEndingEvents end local sessions.

View Source
var DefaultEventsRequested = []string{
	Event["sessionRevoked"], Event["credentialChange"], Event["assuranceLevelChange"], Event["tokenClaimsChange"],
	Event["accountDisabled"], Event["accountEnabled"], Event["accountPurged"], Event["credentialCompromise"],
	Event["sessionsRevoked"], Event["accountCredentialChangeRequired"],
}

DefaultEventsRequested is the poll stream's events_requested when the caller does not name one.

View Source
var DefaultIDTokenSigningAlgs = []string{"RS256"}

DefaultIDTokenSigningAlgs is the ID token algorithm allow-list when the configuration names none: RS256 only.

View Source
var Event = map[string]string{
	"sessionRevoked":                  caepPrefix + "session-revoked",
	"tokenClaimsChange":               caepPrefix + "token-claims-change",
	"credentialChange":                caepPrefix + "credential-change",
	"assuranceLevelChange":            caepPrefix + "assurance-level-change",
	"deviceComplianceChange":          caepPrefix + "device-compliance-change",
	"sessionEstablished":              caepPrefix + "session-established",
	"sessionPresented":                caepPrefix + "session-presented",
	"riskLevelChange":                 caepPrefix + "risk-level-change",
	"accountCredentialChangeRequired": riscPrefix + "account-credential-change-required",
	"accountPurged":                   riscPrefix + "account-purged",
	"accountDisabled":                 riscPrefix + "account-disabled",
	"accountEnabled":                  riscPrefix + "account-enabled",
	"identifierChanged":               riscPrefix + "identifier-changed",
	"identifierRecycled":              riscPrefix + "identifier-recycled",
	"credentialCompromise":            riscPrefix + "credential-compromise",
	"optIn":                           riscPrefix + "opt-in",
	"optOutInitiated":                 riscPrefix + "opt-out-initiated",
	"optOutCancelled":                 riscPrefix + "opt-out-cancelled",
	"optOutEffective":                 riscPrefix + "opt-out-effective",
	"recoveryActivated":               riscPrefix + "recovery-activated",
	"recoveryInformationChanged":      riscPrefix + "recovery-information-changed",
	"sessionsRevoked":                 riscPrefix + "sessions-revoked",
	"verification":                    ssfPrefix + "verification",
	"streamUpdated":                   ssfPrefix + "stream-updated",
}

Event is the CAEP, RISC, and SSF event type each short name refers to.

View Source
var SupportedJWSAlgs = []string{
	"RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512", "EdDSA", "Ed25519",
}

SupportedJWSAlgs are the algorithms a Security Event Token may use.

Functions

func AllowedIDTokenAlgorithms

func AllowedIDTokenAlgorithms(advertised []string, pinned string, allowed []string) ([]string, error)

AllowedIDTokenAlgorithms is the set of ID token algorithms this client accepts: the pinned one when there is one, else the allow-list (RS256 when empty), each kept only when the provider advertises it too. "none" is never accepted, and a symmetric algorithm only when it is named.

func ApplyClientAuth

func ApplyClientAuth(config map[string]any, key any, body map[string]string, headers map[string]string, audience string) error

ApplyClientAuth adds this client's authentication. A client assertion's audience is the issuer.

func B64URLDecode

func B64URLDecode(value, what string) ([]byte, error)

func B64URLEncode

func B64URLEncode(data []byte) string

func CodeChallengeS256

func CodeChallengeS256(verifier string) string

CodeChallengeS256 is RFC 7636 S256: base64url(SHA-256(verifier)), with no padding.

func DiscoverProvider

func DiscoverProvider(metadataURL string, tlsOpt map[string]string) (map[string]any, error)

func FetchJWKS

func FetchJWKS(jwksURI string, tlsOpt map[string]string) ([]map[string]any, error)

func HTU

func HTU(rawURL string) string

HTU is the htu of a proof: the request URL without its query and fragment.

func HashClaim

func HashClaim(value, alg string) string

HashClaim is the left half of the digest the algorithm names, base64url, no padding.

func IDTokenAlgorithms

func IDTokenAlgorithms(advertised []string, pinned string) ([]string, error)

IDTokenAlgorithms is AllowedIDTokenAlgorithms with the default allow-list.

func IssuerFromMetadataURL

func IssuerFromMetadataURL(metadataURL string) (string, error)

func LoadPrivateKey

func LoadPrivateKey(pemText, alg string) (any, error)

func PublicKeyFromJWK

func PublicKeyFromJWK(jwk map[string]any) (any, error)

func RandomToken

func RandomToken() (string, error)

RandomToken is 32 random bytes, base64url. A PKCE verifier and a state or nonce.

func ReadConfigFile

func ReadConfigFile(path string) (map[string]any, error)

ReadConfigFile reads a configuration file. Relative paths start in the file's directory.

func ResolveConfig

func ResolveConfig(raw map[string]any, baseDir string) (map[string]any, error)

ResolveConfig reads a configuration object and fills the defaults. baseDir is where relative paths start. signals is omitted when CAEP and RISC are on, and present as false when they are off.

func SignJWS

func SignJWS(key any, alg string, input []byte) ([]byte, error)

func SubjectOf

func SubjectOf(subID map[string]any, issuer string) map[string]string

SubjectOf reads an event's subject. A complex subject's user is the person and its session the provider session.

func TrackedFromLogin

func TrackedFromLogin(localID string, login *Login, expiresAt *float64) map[string]any

TrackedFromLogin is what an OpenID Connect sign-in says about the session, for the index.

func ValidateIDToken

func ValidateIDToken(token string, checks tokenChecks) (map[string]any, error)

ValidateIDToken verifies an ID token and returns its payload.

func ValidateProviderMetadata

func ValidateProviderMetadata(raw map[string]any, expectedIssuer string) (map[string]any, error)

func VerifyCompactJWS

func VerifyCompactJWS(token string, keys []map[string]any) (map[string]any, map[string]any, error)

VerifyCompactJWS verifies a compact JWS against the keys of a JWKS and returns its header and payload. The key comes from the JWKS, never from the token.

func VerifySignature

func VerifySignature(key any, alg string, input, signature []byte) bool

VerifySignature reports whether signature matches. A malformed signature is a miss.

func WellKnownURLs

func WellKnownURLs(issuer, suffix string) []string

Types

type Access

type Access struct {
	AccessToken string
	TokenType   string
	ExpiresAt   float64
	HasExpires  bool
	Scope       string
}

Access is a client-credentials token.

type AuthorizeOptions

type AuthorizeOptions struct {
	RedirectURI string
	Scope       string
	Prompt      string
	LoginHint   string
	MaxAge      *float64
	ACRValues   string
	ExpectedSub string
}

AuthorizeOptions are the optional Authentication Request parameters. RedirectURI is held to the same rule as the configured one. ACRValues replaces the acrValues setting for this request.

type EndSessionOptions

type EndSessionOptions struct {
	IDToken    string
	PostLogout *string
	State      string
	LogoutHint string
}

EndSessionOptions builds an RP-Initiated Logout URL. A nil PostLogout uses the configuration's post-logout redirect.

type Logger

type Logger interface {
	Info(message string)
	Warn(message string)
	Error(message string)
}

Logger receives receiver progress. The default writes a line.

type Login

type Login struct {
	Subject           string
	Issuer            string
	Claims            map[string]any
	AccessToken       string
	IDToken           string
	TokenType         string
	Email             string
	Name              string
	PreferredUsername string
	SID               string
	RefreshToken      string
	ExpiresAt         float64
	HasExpires        bool
	Scope             string
	// Session is the session-cache handle (CompleteSession), or "".
	Session string
}

Login is a completed sign-in. Tokens stay in this process.

type MemorySessionStore

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

MemorySessionStore is the default SessionStore: this process's memory.

func NewMemorySessionStore

func NewMemorySessionStore() *MemorySessionStore

func (*MemorySessionStore) Delete

func (m *MemorySessionStore) Delete(sessionID string) error

func (*MemorySessionStore) Get

func (m *MemorySessionStore) Get(sessionID string) (*Login, error)

func (*MemorySessionStore) Len

func (m *MemorySessionStore) Len() int

Len is the number of sessions held.

func (*MemorySessionStore) Set

func (m *MemorySessionStore) Set(sessionID string, login *Login) error

type OidcError

type OidcError struct {
	Code       string
	Message    string
	OAuthError string
	Cause      error
}

OidcError is every failure this module reports. Code is config, discovery, protocol, validation, signature, session, or ssf. OAuthError is the OAuth error code when the provider named one.

func (*OidcError) Error

func (e *OidcError) Error() string

func (*OidcError) Unwrap

func (e *OidcError) Unwrap() error

type ReceiverOptions

type ReceiverOptions struct {
	TLS             map[string]string
	Client          *RelyingParty
	Scope           string
	Headers         func() map[string]string
	EventsRequested []string
	EndOn           []string
	Index           *SessionIndex
	Description     string
	PollIntervalMs  int
	MaxEvents       int
	Log             Logger
}

ReceiverOptions are the optional parts of a SignalsReceiver. Client makes every call to the transmitter with Client's client-credentials token for Scope (default ssf.manage), with a DPoP proof when that token is DPoP-bound, and clears the session cache entry of every session an event ends. Headers, when Client is nil, supplies the headers instead.

type RelyingParty

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

RelyingParty is a confidential OpenID Connect client.

func Create

func Create(config map[string]any) (*RelyingParty, error)

Create discovers the provider, or uses metadata already loaded, and returns a client.

func FromFile

func FromFile(path string) (*RelyingParty, error)

func (*RelyingParty) Authorize

func (rp *RelyingParty) Authorize() (*Transaction, error)

Authorize builds the Authentication Request. Keep the transaction until Complete.

func (*RelyingParty) AuthorizeOptions

func (rp *RelyingParty) AuthorizeOptions(opts AuthorizeOptions) (*Transaction, error)

func (*RelyingParty) ClientCredentials

func (rp *RelyingParty) ClientCredentials(scope string) (Access, error)

ClientCredentials performs the client-credentials grant and caches the token until shortly before it expires.

func (*RelyingParty) Complete

func (rp *RelyingParty) Complete(query map[string]string, txn *Transaction) (*Login, error)

Complete exchanges the code from the redirect URI. A code is accepted once.

func (*RelyingParty) CompleteSession

func (rp *RelyingParty) CompleteSession(query map[string]string, txn *Transaction, sessionID string) (*Login, error)

CompleteSession is Complete, and keeps the sign-in's tokens in the session store under sessionID. An empty sessionID makes a new handle. The handle is Login.Session either way.

func (*RelyingParty) Config

func (rp *RelyingParty) Config() map[string]any

func (*RelyingParty) DPoPEnabled

func (rp *RelyingParty) DPoPEnabled() bool

DPoPEnabled reports whether this client sends DPoP proofs.

func (*RelyingParty) DPoPThumbprint

func (rp *RelyingParty) DPoPThumbprint() string

DPoPThumbprint is the RFC 7638 thumbprint of the DPoP key (dpop_jkt), or "".

func (*RelyingParty) EndSessionURL

func (rp *RelyingParty) EndSessionURL(opts EndSessionOptions) string

EndSessionURL is the RP-Initiated Logout URL, or "" when the provider has no end-session endpoint.

func (*RelyingParty) Metadata

func (rp *RelyingParty) Metadata() map[string]any

func (*RelyingParty) Refresh

func (rp *RelyingParty) Refresh(refreshToken, scope string, previous *Login) (*Login, error)

Refresh performs the refresh-token grant. A new ID token's subject is checked against previous.

func (*RelyingParty) RemoveSession

func (rp *RelyingParty) RemoveSession(sessionID string) error

RemoveSession clears a session's tokens: sign-out, or a CAEP session-revoked.

func (*RelyingParty) ResourceRequest

func (rp *RelyingParty) ResourceRequest(method, rawURL, accessToken, tokenType string, headers map[string]string, body *string) (status int, contentType string, responseBody string, err error)

ResourceRequest calls a protected resource with an access token. A token whose type is DPoP is sent as "DPoP <token>" with a proof carrying ath, and a 401 asking for a DPoP nonce is retried once with the nonce the response gave. Any other token is sent as a Bearer token.

func (*RelyingParty) Session

func (rp *RelyingParty) Session(sessionID string) (*Login, error)

Session is the sign-in a session holds, or nil.

func (*RelyingParty) SessionAccessToken

func (rp *RelyingParty) SessionAccessToken(sessionID string) (Access, error)

SessionAccessToken returns a valid access token for a session: the cached one while it has more than 30 seconds left, otherwise one obtained with the refresh token (with a DPoP proof when DPoP is in use), and the cache is updated. A failed refresh removes the session and is refused.

func (*RelyingParty) SessionStore

func (rp *RelyingParty) SessionStore() SessionStore

SessionStore is the store CompleteSession writes to.

func (*RelyingParty) SetSessionStore

func (rp *RelyingParty) SetSessionStore(store SessionStore)

SetSessionStore replaces the session store. Call it before the first sign-in.

func (*RelyingParty) TLS

func (rp *RelyingParty) TLS() map[string]string

func (*RelyingParty) UserInfo

func (rp *RelyingParty) UserInfo(accessToken, expectedSub string) (map[string]any, error)

UserInfo calls UserInfo and checks that sub is expectedSub.

type SessionIndex

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

SessionIndex is one process's memory of local sessions, bounded: expired sessions go first, then the oldest.

func NewSessionIndex

func NewSessionIndex(maxSessions int) *SessionIndex

func (*SessionIndex) Add

func (s *SessionIndex) Add(session map[string]any)

func (*SessionIndex) ByEmail

func (s *SessionIndex) ByEmail(email string) []string

func (*SessionIndex) ByIDPSession

func (s *SessionIndex) ByIDPSession(idpSession string) []string

func (*SessionIndex) ByPerson

func (s *SessionIndex) ByPerson(person string) []string

func (*SessionIndex) Remove

func (s *SessionIndex) Remove(localID string)

type SessionStore

type SessionStore interface {
	Get(sessionID string) (*Login, error)
	Set(sessionID string, login *Login) error
	Delete(sessionID string) error
}

SessionStore holds the tokens of completed sign-ins, keyed by a session identifier the application chooses. Get answers nil and no error for a session it does not hold. The default is MemorySessionStore; an application that runs several processes replaces it with a shared store.

type SignalEvent

type SignalEvent struct {
	Type     string
	Payload  map[string]any
	Subject  map[string]string
	JTI      string
	Sessions []string
	Ended    bool
	IAT      *float64
	Txn      string
}

SignalEvent is one event from a Security Event Token.

type SignalsReceiver

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

SignalsReceiver finds or creates this application's poll stream and turns events into local sessions.

func NewSignalsReceiver

func NewSignalsReceiver(transmitter string, onEnd func([]string, SignalEvent), opts ReceiverOptions) (*SignalsReceiver, error)

func (*SignalsReceiver) On

func (r *SignalsReceiver) On(eventType string, handler func(SignalEvent)) *SignalsReceiver

func (*SignalsReceiver) PollOnce

func (r *SignalsReceiver) PollOnce() (bool, error)

PollOnce is one poll. A call while a poll is in flight joins it.

func (*SignalsReceiver) Start

func (r *SignalsReceiver) Start() error

Start finds the transmitter and the stream, then polls until Stop.

func (*SignalsReceiver) Stop

func (r *SignalsReceiver) Stop()

Stop stops polling. Acknowledgements not yet sent go out on the next Start's first poll. It waits until the poll loop has left, so a later PollOnce is not the poll Start already had in flight.

func (*SignalsReceiver) Stream

func (r *SignalsReceiver) Stream() map[string]any

Stream is the stream the receiver is polling, once started.

func (*SignalsReceiver) Track

func (r *SignalsReceiver) Track(session map[string]any)

func (*SignalsReceiver) Untrack

func (r *SignalsReceiver) Untrack(localID string)

func (*SignalsReceiver) Verify

func (r *SignalsReceiver) Verify(state string) error

Verify asks the transmitter for a verification event.

type Transaction

type Transaction struct {
	State        string
	Nonce        string
	CodeVerifier string
	RedirectURI  string
	URL          string
	MaxAge       *float64
	ExpectedSub  string
	// ACRValues are the acr_values requested, space-separated. Complete
	// requires the ID token's acr to be one of them.
	ACRValues string
}

Transaction is the sign-in kept until the browser returns.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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