oidclient

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: Apache-2.0 Imports: 13 Imported by: 3 modules, 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

oidclient

CI Go Reference Go Report Card License

Experimental — internal use. This library is developed for infodancer projects that authenticate against infodancer/webauth. The API is unstable and may change without notice. If you're looking for a general-purpose OIDC relying party library for Go, consider coreos/go-oidc.

A thin convenience wrapper around coreos/go-oidc and golang.org/x/oauth2 that bundles OIDC discovery, JWKS-based JWT validation, the authorization code flow with PKCE, and cookie management into a single Client type. No custom cryptography — all signing and verification is delegated to go-oidc and go-jose.

Features

  • OIDC autodiscovery via go-oidc Provider
  • JWKS caching and key rotation handled by go-oidc
  • RS256 JWT validation with issuer and expiry enforcement
  • PKCE (S256) via x/oauth2
  • Authorization code flow — authorize URL, token exchange, ID token verification
  • RFC 7591 dynamic client registration — automatic at startup when the provider advertises it
  • Static confidential clients — set ClientID + ClientSecret for providers that issue a secret and don't support RFC 7591 (e.g. Google)
  • Cookie helpers — secure defaults for OAuth flow state and JWT session cookies

Install

go get github.com/infodancer/oidclient

Usage

Creating a client
client, err := oidclient.New(ctx, oidclient.Config{
    IssuerURL:   "https://auth.example.com/t/mytenant",
    CookieName:  "myapp_jwt",
    ClientID:    "myapp",       // pre-registered fallback; ignored if the provider supports RFC 7591
    ClientName:  "My App",      // sent during dynamic registration (optional)
    CallbackURL: "https://myapp.example.com/auth/callback",
})
Dynamic client registration (RFC 7591)

If the provider's discovery document advertises registration_endpoint, New performs RFC 7591 dynamic client registration during startup, posts client metadata (client_name, redirect_uris), and uses the server-assigned client_id (and client_secret, if returned) for all subsequent operations. The runtime id is available via client.ClientID() for persistence across restarts:

log.Printf("registered as client_id=%s", client.ClientID())

When the provider does not advertise registration_endpoint, Config.ClientID is used as-is — the manual-provisioning case (the OIDC client was registered out-of-band at the provider's admin console). For a confidential client that also issues a secret (e.g. a Google "Web application" credential), set Config.ClientSecret alongside ClientID; it is sent in the token-exchange request body together with the PKCE verifier. Leave it empty for public PKCE clients. If the provider does advertise registration_endpoint, dynamic registration runs and the server-assigned secret supersedes ClientSecret.

Starting the login flow
func handleLogin(w http.ResponseWriter, r *http.Request) {
    verifier := oidclient.GenerateVerifier()
    state, _ := oidclient.GenerateNonce()
    secure := oidclient.IsSecure(r)

    oidclient.SetFlowCookie(w, oidclient.CookieVerifier, verifier, secure)
    oidclient.SetFlowCookie(w, oidclient.CookieState, state, secure)
    oidclient.SetFlowCookie(w, oidclient.CookieRedirect, r.URL.RequestURI(), secure)

    http.Redirect(w, r, client.AuthorizeURL(state, verifier), http.StatusFound)
}
Handling the callback
func handleCallback(w http.ResponseWriter, r *http.Request) {
    state := r.URL.Query().Get("state")
    if state != oidclient.FlowCookieValue(r, oidclient.CookieState) {
        http.Error(w, "invalid state", http.StatusBadRequest)
        return
    }

    verifier := oidclient.FlowCookieValue(r, oidclient.CookieVerifier)
    accessToken, claims, err := client.ExchangeCode(r.Context(), r.URL.Query().Get("code"), verifier)
    if err != nil {
        http.Error(w, "auth failed", http.StatusBadGateway)
        return
    }

    // claims.Sub, claims.Email, claims.Name, claims.Roles are available
    // for user provisioning here.

    secure := oidclient.IsSecure(r)
    oidclient.SetSessionCookie(w, client.CookieName(), accessToken, secure)
    oidclient.ClearFlowCookies(w)

    redirectTo := oidclient.FlowCookieValue(r, oidclient.CookieRedirect)
    if redirectTo == "" {
        redirectTo = "/"
    }
    http.Redirect(w, r, redirectTo, http.StatusFound)
}
Validating requests
func requireAuth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        claims, err := client.ValidateCookie(r)
        if err != nil {
            // redirect to login...
            return
        }
        // claims.Sub, claims.Email, claims.Name, claims.Roles available
        next.ServeHTTP(w, r)
    })
}

License

Apache-2.0 — see LICENSE. Vulnerability reporting in SECURITY.md.

Documentation

Overview

Package oidclient is an OIDC relying party library for web applications authenticating against an OpenID Connect provider (designed for use with infodancer/webauth but compatible with any spec-compliant IdP).

It wraps github.com/coreos/go-oidc/v3 for discovery, JWKS, and token verification, and golang.org/x/oauth2 for the authorization code flow with PKCE. Cookie helpers and a convenience API are layered on top.

Index

Constants

View Source
const (
	// Default cookie names for the OIDC authorization flow.
	CookieVerifier = "oauth_verifier"
	CookieState    = "oauth_state"
	CookieRedirect = "oauth_redirect"
)

Variables

View Source
var (
	ErrNoCookie   = errors.New("oidclient: missing auth cookie")
	ErrNoIDToken  = errors.New("oidclient: token response missing id_token")
	ErrMissingSub = errors.New("oidclient: token missing sub claim")
)

Sentinel errors returned by Validate, ValidateCookie, and ExchangeCode.

Functions

func ClearFlowCookies

func ClearFlowCookies(w http.ResponseWriter)

ClearFlowCookies expires all OIDC flow cookies.

func ClearSessionCookie

func ClearSessionCookie(w http.ResponseWriter, name string, secure bool)

ClearSessionCookie expires the session cookie.

func FlowCookieValue

func FlowCookieValue(r *http.Request, name string) string

FlowCookieValue reads a named cookie value, returning "" if absent.

func GenerateNonce

func GenerateNonce() (string, error)

GenerateNonce returns a random base64url-encoded state nonce for CSRF protection.

func GenerateVerifier

func GenerateVerifier() string

GenerateVerifier returns a random PKCE code verifier (RFC 7636). The verifier should be stored (e.g. in a cookie) and passed to both AuthorizeURL and ExchangeCode.

func GetOrCreateFlow added in v0.2.0

func GetOrCreateFlow(w http.ResponseWriter, r *http.Request, returnTo string) (state, verifier string, err error)

GetOrCreateFlow returns the state and PKCE verifier for the current authorization flow, generating them and setting the flow cookies when no flow is in progress. An existing flow (both state and verifier cookies present) is reused, so concurrent unauthenticated requests share one flow instead of overwriting the state another in-flight redirect depends on. The redirect cookie is always set to returnTo: state and verifier are per-flow, the post-login destination follows the latest request.

func IsSecure

func IsSecure(r *http.Request) bool

IsSecure returns true if the request arrived over TLS or via an HTTPS proxy.

func SetFlowCookie

func SetFlowCookie(w http.ResponseWriter, name, value string, secure bool)

SetFlowCookie writes an HttpOnly cookie used during the OIDC flow. The cookie is session-lifetime: the flow must survive however long the user leaves the IdP's login page open, and the state/verifier nonces derive no security from a fixed expiry -- the authorization code and PKCE binding do.

func SetSessionCookie

func SetSessionCookie(w http.ResponseWriter, name, token string, secure bool)

SetSessionCookie writes the JWT as an HttpOnly session cookie.

Types

type Claims

type Claims struct {
	Sub           string   `json:"sub"`
	Email         string   `json:"email"`
	EmailVerified bool     `json:"email_verified,omitempty"`
	Name          string   `json:"name"`
	Roles         []string `json:"roles,omitempty"`
}

Claims holds the JWT claims extracted from an ID or access token.

type Client

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

Client is an OIDC relying party that performs authorization code flows with PKCE and validates JWTs using keys from the provider's JWKS endpoint.

Discovery, JWKS caching, and signature verification are handled by github.com/coreos/go-oidc/v3. The authorization code flow is handled by golang.org/x/oauth2.

func New

func New(ctx context.Context, cfg Config) (*Client, error)

New creates a Client by performing OIDC discovery against the configured IssuerURL. Returns an error if discovery fails or the configuration is incomplete.

func (*Client) AuthorizeURL

func (c *Client) AuthorizeURL(state, verifier string) string

AuthorizeURL builds the OIDC authorization URL with PKCE. verifier is the PKCE code verifier (store it for the callback); the S256 challenge is computed automatically.

func (*Client) ClientID

func (c *Client) ClientID() string

ClientID returns the OIDC client ID in effect for this Client. When the provider supports RFC 7591 dynamic registration, this is the server-assigned id (which may differ from Config.ClientID); otherwise it is the pre-registered id from Config.

func (*Client) CookieName

func (c *Client) CookieName() string

CookieName returns the configured session cookie name.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, code, verifier string) (accessToken string, claims *Claims, err error)

ExchangeCode exchanges an authorization code for tokens using the PKCE verifier. Returns the access token (for session storage) and the verified claims from the ID token.

func (*Client) FlowConfigured

func (c *Client) FlowConfigured() bool

FlowConfigured reports whether the OIDC authorization code flow is configured (i.e., ClientID and CallbackURL are set).

func (*Client) LoginURL

func (c *Client) LoginURL(redirectPath string) string

LoginURL returns a URL to redirect unauthenticated users to the IdP login.

func (*Client) LogoutURL

func (c *Client) LogoutURL() string

LogoutURL returns the IdP logout URL.

func (*Client) RegisterURL

func (c *Client) RegisterURL(state, verifier string) string

RegisterURL builds the URL to the IdP's registration page with the OIDC parameters needed to complete an authorization code flow after signup. The verifier is the same PKCE code verifier used with ExchangeCode. After registration, the IdP redirects to CallbackURL with an authorization code, identical to the login flow.

func (*Client) Validate

func (c *Client) Validate(ctx context.Context, tokenStr string) (*Claims, error)

Validate parses and validates a raw access token JWT, returning the extracted claims. The token's signature is verified against the provider's JWKS, and standard claims (issuer, expiry) are checked.

func (*Client) ValidateCookie

func (c *Client) ValidateCookie(r *http.Request) (*Claims, error)

ValidateCookie extracts the JWT from the session cookie and validates it. Returns ErrNoCookie if the cookie is absent.

type Config

type Config struct {
	// IssuerURL is the OIDC issuer (e.g. "https://auth.example.com/t/mytenant").
	// Used for discovery and token verification. Required.
	IssuerURL string

	// CookieName is the name of the HttpOnly cookie storing the JWT session token.
	CookieName string

	// ClientID is this application's pre-registered OIDC client ID. Used as-is
	// when the provider does not advertise a registration_endpoint. When the
	// provider supports RFC 7591 dynamic client registration, this field is
	// ignored and the server-assigned client_id is used instead — query the
	// runtime value via Client.ClientID after New returns.
	ClientID string

	// ClientName is optional client metadata (RFC 7591 §2) sent during dynamic
	// registration. Servers may use it for display in admin UIs and consent
	// screens. Ignored when the provider does not advertise a registration_endpoint.
	ClientName string

	// ClientSecret is the static secret for a confidential client (e.g. a Google
	// "Web application" credential). Set it together with a pre-registered
	// ClientID for providers that issue a secret and do not support RFC 7591
	// dynamic registration; it is sent in the token-exchange request body
	// alongside the PKCE verifier. Leave empty for public PKCE clients. When the
	// provider advertises a registration_endpoint, dynamic registration runs and
	// the server-assigned secret supersedes this value.
	ClientSecret string

	// CallbackURL is the registered redirect URI for the authorization code flow.
	CallbackURL string

	// WebauthURL is the base URL of the auth server (e.g. "https://auth.example.com").
	// Used for LoginURL/LogoutURL construction. Derived from IssuerURL if empty.
	WebauthURL string

	// HTTPClient overrides the default HTTP client for OIDC discovery, JWKS
	// fetches, and token exchange requests.
	HTTPClient *http.Client
}

Config configures the OIDC client.

Jump to

Keyboard shortcuts

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