Documentation
¶
Overview ¶
Package oidcclient signs people in to a Go web app through any OpenID Connect server (ubgo/auth's plugin/oauthprovider, Google, Keycloak, Entra) and keeps them signed in for days, while the login server keeps the final say on every request.
The model has two clocks. The session lives long (Lifetimes: 7 days idle, 30 days absolute by default), so closing the browser does not sign anyone out. The login server is asked again at most every recheck interval (1 minute by default) while the person is active, by refreshing the token (or by introspection, userinfo, or back-channel logout alone). A "no" from the server ends the session at the next request, whatever cookie the browser still holds; a copy of an old cookie is worth nothing once the server refuses its refresh token.
The minimal setup is New with a Config, then mounting Client.Handler for the login, callback, logout and back-channel routes and wrapping the app's handlers with Client.Require. Every policy (session storage, sealing, user mapping, authorization, the re-check method, the outage grace, lifetimes, responses, return URLs, cookies, routes and plumbing) is one typed option with a safe default. The protocol floors (PKCE S256, state, nonce, the ID token signature under an allow-listed algorithm, iss, aud, exp and azp, constant-time comparisons, same-site return URLs, hook errors failing closed) have no option at all: there is nothing to turn off.
The package depends only on the Go standard library, so an app that imports it downloads nothing else. DESIGN.md beside this file explains the request lifecycle and why each seam has the shape it has.
Index ¶
- Constants
- Variables
- func DefaultScopes() []string
- func IsPageRequest(r *http.Request) bool
- type AuthorizeRequest
- type Authorizer
- type Claims
- type Client
- func (c *Client) BackchannelHandler() http.Handler
- func (c *Client) CallbackHandler() http.Handler
- func (c *Client) Handler() http.Handler
- func (c *Client) LoginHandler() http.Handler
- func (c *Client) LogoutHandler() http.Handler
- func (c *Client) Optional(next http.Handler) http.Handler
- func (c *Client) Provider() *Provider
- func (c *Client) Require(next http.Handler) http.Handler
- type ClientAuth
- type ClientAuthFunc
- type ClientAuthRequest
- type Config
- type CookieOptions
- type Decision
- type Event
- type EventKind
- type Identity
- type IntrospectRequest
- type Introspection
- type Lifetimes
- type LogoutTarget
- type MapReason
- type MapUserRequest
- type MemoryStore
- func (m *MemoryStore) Delete(_ context.Context, s Session) error
- func (m *MemoryStore) Load(_ context.Context, cookieValue []byte) (Session, error)
- func (m *MemoryStore) RevokeSessions(_ context.Context, t LogoutTarget) (int, error)
- func (m *MemoryStore) Save(_ context.Context, s Session) ([]byte, error)
- type Observer
- type ObserverFunc
- type Option
- func WithAuthParams(params map[string]string) Option
- func WithAuthorizer(a Authorizer) Option
- func WithClientAuth(a ClientAuth) Option
- func WithClock(now func() time.Time) Option
- func WithCookie(o CookieOptions) Option
- func WithDiscovery(m ProviderMetadata) Option
- func WithHTTPClient(c *http.Client) Option
- func WithLifetimes(l Lifetimes) Option
- func WithLogger(l *slog.Logger) Option
- func WithObserver(o Observer) Option
- func WithOutageGrace(d time.Duration) Option
- func WithPaths(p Paths) Option
- func WithPostLogoutPath(path string) Option
- func WithRecheckInterval(d time.Duration) Option
- func WithRechecker(r Rechecker) Option
- func WithResponder(r Responder) Option
- func WithReturnPolicy(p ReturnPolicy) Option
- func WithScopes(scopes ...string) Option
- func WithSealer(sl Sealer) Option
- func WithSessionStore(st SessionStore) Option
- func WithUserMapper(m UserMapper) Option
- type Paths
- type Provider
- func (p *Provider) Introspect(ctx context.Context, in IntrospectRequest) (Introspection, error)
- func (p *Provider) Metadata(ctx context.Context) (ProviderMetadata, error)
- func (p *Provider) Refresh(ctx context.Context, in RefreshRequest) (*Refreshed, error)
- func (p *Provider) UserInfo(ctx context.Context, accessToken Secret, subject string) (Claims, error)
- type ProviderMetadata
- type Reason
- type RecheckRequest
- type RecheckResult
- type Rechecker
- type RecheckerFunc
- type RefreshRequest
- type Refreshed
- type Refusal
- type RefusalKind
- type Responder
- type ResponderFunc
- type ReturnPolicy
- type ReturnRequest
- type Sealer
- type Secret
- type Session
- type SessionRevoker
- type SessionStore
- type TokenTypeHint
- type Tokens
- type User
- type UserMapper
Examples ¶
Constants ¶
const ( DefaultCookieName = "__Host-oidc_session" // FlowCookieSuffix names the sign-in flow cookie after the session's: // "__Host-oidc_session_flow". FlowCookieSuffix = "_flow" )
Cookie name defaults and prefixes (RFC 6265bis cookie prefixes).
const ( ClaimSubject = "sub" ClaimIssuer = "iss" ClaimEmail = "email" ClaimEmailVerified = "email_verified" ClaimName = "name" ClaimSessionID = "sid" )
Standard claim names the package reads (OpenID Connect Core section 5.1, Front- and Back-Channel Logout).
const ( // DefaultRecheckInterval is how long the login server's last "yes" // stands: a person removed at the server is refused by the app within // this long, even with a saved cookie. //ds:def id=defaultrecheckinterval-vekfr6zh owner=@khanakia stability=stable DefaultRecheckInterval = time.Minute // RecheckEveryRequest, given to WithRecheckInterval, asks the login // server on every request: strict, and one round trip per request. RecheckEveryRequest time.Duration = 0 // DefaultOutageGrace is how long the last "yes" still stands while the // login server cannot be reached, counted from Session.CheckedAt. After // it, requests are answered "unavailable" (the session is kept, so the // person is back the moment the server answers). //ds:def id=defaultoutagegrace-asgxt3qs owner=@khanakia stability=stable DefaultOutageGrace = 5 * time.Minute // NoOutageGrace, given to WithOutageGrace, refuses as soon as the login // server cannot be reached. NoOutageGrace time.Duration = 0 )
Re-check timing defaults.
const ( //ds:def id=defaultidlelifetime-mjhkz59a owner=@khanakia stability=stable DefaultIdleLifetime = 7 * 24 * time.Hour //ds:def id=defaultabsolutelifetime-957evyy7 owner=@khanakia stability=stable DefaultAbsoluteLifetime = 30 * 24 * time.Hour )
Default lifetimes: a person who closes the browser on Monday and comes back on Wednesday is still signed in; nobody stays signed in past a month without passing the login server again.
const ( // DefaultRoutePrefix is where the routes live unless WithPaths moves // them: /auth/login, /auth/callback, /auth/logout, /auth/backchannel. DefaultRoutePrefix = "/auth" )
Route names under a prefix.
const MinSecretSize = 32
MinSecretSize is the shortest secret NewSecretSealer accepts: 32 bytes, the AES-256 key size, so the derived key never has less entropy than its cipher. Generate one with `openssl rand -base64 32` and decode it.
const ParamReturnTo = "return_to"
ParamReturnTo is the login route's query parameter naming where to go after sign-in. The middleware sets it to the refused request's path and query; the ReturnPolicy decides what is used.
const ScopeOpenID = "openid"
ScopeOpenID is always requested, whatever WithScopes says: without it there is no ID token and nothing to verify.
Variables ¶
var ( // ErrInvalidConfig is returned by New for a Config or an option that // cannot be used safely: a missing field, an http issuer or app URL on a // non-loopback host, conflicting options, a cookie name the browser // would reject. The wrapped text names the field. ErrInvalidConfig = errors.New("oidcclient: invalid configuration") // ErrNilOption is recorded by an option given a nil func, interface or // pointer, so New fails at start-up naming the option instead of the // first request panicking on it. ErrNilOption = errors.New("oidcclient: nil option value") // ErrNoSession is what a SessionStore's Load answers for a cookie value // that names no live session (deleted, expired, revoked by back-channel // logout). The middleware treats it as "not signed in", never as a // failure. ErrNoSession = errors.New("oidcclient: no session") // ErrAccessDenied is the refusal a UserMapper or an Authorizer returns // (or wraps) to say "this person may not use the app". It is answered // with the no-access response. Any other error refuses too, but is // answered and logged as a failure, so an outage of the app's own user // database is not shown to the person as a permanent "no". ErrAccessDenied = errors.New("oidcclient: access denied") // server: a network error, a timeout, a 5xx, an unreadable body. Only an // error wrapping it starts the outage grace (WithOutageGrace); a // Rechecker that fails for another reason refuses at once. A custom // Rechecker wraps it when, and only when, the server could not be asked. ErrProviderUnavailable = errors.New("oidcclient: login server unavailable") // ErrProviderRefused is the login server answering "no": invalid_grant // on a refresh, 401 from userinfo, a token endpoint that refuses the // client. It ends the session; it never starts the outage grace. ErrProviderRefused = errors.New("oidcclient: login server refused") // ErrBackchannelUnsupported is answered by the back-channel logout route // when the SessionStore cannot find sessions by subject or provider // session (it does not implement SessionRevoker), so the login server's // log shows why its logout token did nothing. The default cookie store // is one such store; NewMemoryStore is not. ErrBackchannelUnsupported = errors.New("oidcclient: session store cannot revoke by subject or sid") // ErrSessionTooLarge is a session whose sealed form does not fit the // cookie store's limit (a few cookies of 4 KB each). Sign-in is refused // rather than writing a cookie the browser would drop silently; a // UserMapper that keeps fewer Claims, or a server-side store, fixes it. ErrSessionTooLarge = errors.New("oidcclient: session too large for the cookie store") // ErrSealedCorrupt is what a Sealer's Open answers (or wraps) for a value // that does not open: tampered, sealed under another cookie name, or // sealed with a key no longer in the ring. It reads as "no session". ErrSealedCorrupt = errors.New("oidcclient: sealed value does not open") )
Errors a caller may branch on with errors.Is. Every other failure is wrapped with its cause for the log and answered as a refusal: the package never turns an unexpected error into a "yes".
var DecisionValues = []Decision{Deny, Allow}
DecisionValues is every Decision.
var EventKindValues = []EventKind{EventLogin, EventRefresh, EventGrace, EventRefuse, EventLogout, EventBackchannelLogout, EventRevokeFailed}
EventKindValues is every EventKind.
var MapReasonValues = []MapReason{MapSignIn, MapRefresh}
MapReasonValues is every MapReason.
var ReasonValues = []Reason{ReasonNoSession, ReasonIdleExpired, ReasonAbsoluteExpired, ReasonServerRefused, ReasonServerDown, ReasonNotAuthorized, ReasonProviderDenied, ReasonBadCallback, ReasonHookFailed, ReasonStoreFailed, ReasonBackchannel, ReasonProviderInvalid}
ReasonValues is every Reason.
var RefusalKindValues = []RefusalKind{RefusalLoginRequired, RefusalNoAccess, RefusalUnavailable, RefusalFailed}
RefusalKindValues is every RefusalKind.
var TokenTypeHintValues = []TokenTypeHint{HintRefreshToken, HintAccessToken}
TokenTypeHintValues is every TokenTypeHint.
Functions ¶
func DefaultScopes ¶
func DefaultScopes() []string
DefaultScopes returns the scopes requested when WithScopes is not given, as a fresh slice the caller may extend.
func IsPageRequest ¶
IsPageRequest reports whether r is a browser navigation that should get a redirect or a page rather than a status and JSON: a GET or HEAD whose Accept header lists text/html. It is the rule DefaultResponder uses, exported for a custom Responder that keeps it.
Types ¶
type AuthorizeRequest ¶
AuthorizeRequest is what an Authorizer decides from: the signed-in User (fresh: the login server said yes within the recheck interval) and the request, for rules by route, method or tenant host.
type Authorizer ¶
type Authorizer func(ctx context.Context, in AuthorizeRequest) (Decision, error)
Authorizer is the app's own rule on top of the login server's: roles, tenant membership, route rules. It runs on every request Client.Require lets through, after the session is known to be fresh. The default is none: the login server alone decides who may use the app.
It fails closed: only (Allow, nil) allows. Any error refuses, an error together with Allow included; ErrAccessDenied is answered as no access, any other error as a failure.
type Claims ¶
type Claims map[string]json.RawMessage
Claims are the members of a verified ID token (or a userinfo answer), each kept as the raw JSON the server sent, so no number, nested object or array is reshaped before the app reads it. The typed accessors cover the common cases; anything else is json.Unmarshal of the raw value.
func (Claims) Bool ¶
Bool returns the claim name as a boolean, and whether it is one. A claim holding the string "true" is not a boolean here: a caller that must accept that spelling (email_verified at some servers) reads both, as DefaultUser does.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the relying party: the four routes, the middleware, and the re-check machinery, for one client at one login server. It is safe for concurrent use and holds no package-level state; an app may run several (two login servers, two clients) side by side under different Paths and cookie names.
func New ¶
New checks cfg and the options and returns a Client. It makes no network call: the discovery document is fetched on first use, so an app starts while the login server is down. Every mistake it can find is returned together, wrapping ErrInvalidConfig or ErrNilOption.
Example ¶
The minimal setup: the login server, the client, the app's origin and a sealing secret. Sessions live in a sealed cookie for 7 days, the login server is asked again every minute, and every route but the four auth routes needs a signed-in person.
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/ubgo/auth/oidcclient"
)
func main() {
c, err := oidcclient.New(oidcclient.Config{
Issuer: "https://login.example.com",
ClientID: "oac_admin",
ClientSecret: oidcclient.Secret(os.Getenv("OIDC_CLIENT_SECRET")),
AppURL: "https://admin.example.com",
SessionSecret: oidcclient.Secret(os.Getenv("SESSION_SECRET")), // 32+ random bytes
})
if err != nil {
log.Fatal(err)
}
app := http.NewServeMux()
app.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
u, _ := oidcclient.UserFrom(r.Context())
fmt.Fprintf(w, "Hello, %s", u.Name)
})
root := http.NewServeMux()
root.Handle(oidcclient.DefaultRoutePrefix+"/", c.Handler()) // /auth/login, /auth/callback, /auth/logout, /auth/backchannel
root.Handle("/", c.Require(app))
log.Fatal(http.ListenAndServe(":8080", root))
}
Output:
func (*Client) BackchannelHandler ¶
BackchannelHandler receives OpenID Connect Back-Channel Logout tokens: a POSTed logout_token signed by the issuer under an allowed algorithm, with iss, aud equal to the client id, iat, a short exp, the back-channel logout event, sub or sid, and no nonce. It ends the matching sessions through the store's SessionRevoker and answers 200; a token that does not verify is 400, a store without SessionRevoker is 501.
Example ¶
Back-channel logout: the login server posts a logout token to AppURL + /auth/backchannel when a person signs out there or is removed, and the sessions it names end at once, cookie or not. It needs a store that can find sessions without their cookie (NewMemoryStore here; Redis or SQL across instances). With it, the periodic re-check can stay as the safety net, or be turned off with RecheckBackchannelOnly.
package main
import (
"log"
"net/http"
"os"
"time"
"github.com/ubgo/auth/oidcclient"
)
func main() {
c, err := oidcclient.New(exampleConfig(),
oidcclient.WithSessionStore(oidcclient.NewMemoryStore()),
oidcclient.WithRecheckInterval(5*time.Minute), // back-channel ends sessions at once; the re-check is the net
)
if err != nil {
log.Fatal(err)
}
// Register https://admin.example.com/auth/backchannel as the client's
// backchannel_logout_uri at the login server. Handler serves it; an app
// that mounts routes one by one mounts it on its own.
mux := http.NewServeMux()
mux.Handle("POST "+oidcclient.PathsUnder(oidcclient.DefaultRoutePrefix).Backchannel, c.BackchannelHandler())
}
// exampleConfig is the Config the examples share.
func exampleConfig() oidcclient.Config {
return oidcclient.Config{
Issuer: "https://login.example.com", ClientID: "oac_admin", AppURL: "https://admin.example.com",
ClientSecret: oidcclient.Secret(os.Getenv("OIDC_CLIENT_SECRET")), SessionSecret: oidcclient.Secret(os.Getenv("SESSION_SECRET")),
}
}
Output:
func (*Client) CallbackHandler ¶
CallbackHandler completes a sign-in: state equal to the flow cookie's (constant time), iss when sent (RFC 9207), the code exchanged with the PKCE verifier, the ID token verified, the UserMapper run, the session saved, the browser sent to the return path. Every failure is refused with RefusalFailed or RefusalNoAccess, and no session is written.
func (*Client) Handler ¶
Handler serves the four routes at Paths: GET Login, GET Callback, POST Logout and POST Backchannel. Any other path is 404, so it can be mounted at "/" of its own mux or under its prefix.
func (*Client) LoginHandler ¶
LoginHandler starts a sign-in: it writes the sealed flow cookie (state, nonce, PKCE verifier, return path) and redirects to the authorization endpoint. GET; the return_to query parameter goes through the ReturnPolicy.
func (*Client) LogoutHandler ¶
LogoutHandler signs out: it deletes the session, revokes its refresh token at the revocation endpoint (RFC 7009, best effort: a failure is logged and observed as EventRevokeFailed, never blocks the sign-out), then sends the browser to the login server's end-session endpoint with the ID token as id_token_hint and the post-logout path, or straight to that path when the server has none. POST only, and only from this origin (Origin or Sec-Fetch-Site), so another site cannot sign people out.
func (*Client) Optional ¶
Optional is Require for pages anyone may see that show more to a signed-in person ("signed in as", a personal menu): it makes the same decision (load, Lifetimes, re-check with the outage grace, the Authorizer) and writes the same cookies, but never refuses. When Require would have let the request through, UserFrom returns the User; otherwise the request goes on without one, and a session the login server refused is ended exactly as under Require. The Responder is never called.
Example ¶
Optional serves pages anyone may see and that show more to a signed-in person. It makes the same decision as Require but never refuses: without a live, re-checked session the page simply gets no User.
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"github.com/ubgo/auth/oidcclient"
)
// exampleRunnableConfig is a Config the runnable examples use: they make
// no call to the login server, because nobody in them is signed in.
func exampleRunnableConfig() oidcclient.Config {
return oidcclient.Config{
Issuer: "https://login.example.com", ClientID: "oac_admin", ClientSecret: "example-only", AppURL: "https://admin.example.com",
SessionSecret: "example-only-session-secret-0123456789",
}
}
func main() {
c, err := oidcclient.New(exampleRunnableConfig())
if err != nil {
log.Fatal(err)
}
home := c.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if u, ok := oidcclient.UserFrom(r.Context()); ok {
fmt.Fprintf(w, "Signed in as %s", u.Name)
return
}
fmt.Fprint(w, "Welcome, guest")
}))
rec := httptest.NewRecorder()
home.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
fmt.Println(rec.Code, rec.Body.String())
}
Output: 200 Welcome, guest
func (*Client) Provider ¶
Provider returns the handle that calls the login server as this client, for the app's own calls (introspection, userinfo) with the same credentials, HTTP client and floors.
func (*Client) Require ¶
Require lets a request through only with a live, fresh, authorized session, and puts its User in the request context (UserFrom). In order: load the session (none: login required), apply Lifetimes (past either: login required), re-check when the last "yes" is older than the recheck interval (single-flight per session; Deny: login required; unreachable: the outage grace, then unavailable), run the UserMapper on a new Identity, run the Authorizer, then serve next. Every refusal goes to the Responder.
Example ¶
Require answers a person who is not signed in by what they asked for: a page is redirected to the login route (which comes back to the page), an API call gets 401 with the login URL in JSON for the SPA to follow.
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"github.com/ubgo/auth/oidcclient"
)
// exampleRunnableConfig is a Config the runnable examples use: they make
// no call to the login server, because nobody in them is signed in.
func exampleRunnableConfig() oidcclient.Config {
return oidcclient.Config{
Issuer: "https://login.example.com", ClientID: "oac_admin", ClientSecret: "example-only", AppURL: "https://admin.example.com",
SessionSecret: "example-only-session-secret-0123456789",
}
}
func main() {
c, err := oidcclient.New(exampleRunnableConfig())
if err != nil {
log.Fatal(err)
}
h := c.Require(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "secret page") }))
page := httptest.NewRequest(http.MethodGet, "/reports?month=11", nil)
page.Header.Set("Accept", "text/html")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, page)
fmt.Println(rec.Code, rec.Header().Get("Location"))
api := httptest.NewRequest(http.MethodGet, "/api/reports", nil)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, api)
fmt.Print(rec.Code, " ", rec.Body.String())
}
Output: 302 /auth/login?return_to=%2Freports%3Fmonth%3D11 401 {"error":"login_required","login_url":"/auth/login?return_to=%2Fapi%2Freports"}
type ClientAuth ¶
type ClientAuth interface {
Authenticate(ctx context.Context, req ClientAuthRequest) error
}
ClientAuth authenticates the client at the login server's endpoints. The default is client_secret_basic with Config.ClientSecret; WithClientAuth sets another: ClientSecretPost, PublicClient, or the app's own for private_key_jwt or a KMS-held key. mTLS needs no ClientAuth: it is the HTTP client's certificate (WithHTTPClient) with PublicClient.
func ClientSecretBasic ¶
func ClientSecretBasic(clientID string, secret Secret) ClientAuth
ClientSecretBasic sends the client id and secret as HTTP Basic (RFC 6749 section 2.3.1), each form-encoded first as the RFC requires. It is what a non-empty Config.ClientSecret means.
func ClientSecretPost ¶
func ClientSecretPost(clientID string, secret Secret) ClientAuth
ClientSecretPost sends the client id and secret in the form body, for a server that does not accept Basic.
func PublicClient ¶
func PublicClient(clientID string) ClientAuth
PublicClient sends only the client id: a client with no secret, which PKCE alone protects, or one authenticated by mTLS. It is explicit, so an empty ClientSecret is never mistaken for a public client.
type ClientAuthFunc ¶
type ClientAuthFunc func(ctx context.Context, req ClientAuthRequest) error
ClientAuthFunc adapts a function to ClientAuth.
func (ClientAuthFunc) Authenticate ¶
func (f ClientAuthFunc) Authenticate(ctx context.Context, req ClientAuthRequest) error
Authenticate calls f.
type ClientAuthRequest ¶
ClientAuthRequest is a token, introspection or revocation request about to be sent, for a ClientAuth to authenticate. Endpoint is the URL it goes to (the audience of a private_key_jwt assertion); Form and Header are sent as they are after Authenticate returns.
type Config ¶
type Config struct {
// Issuer is the login server's issuer URL, exactly as its ID tokens'
// iss and its discovery document say (a trailing slash aside). https,
// or http on a loopback host for local development.
Issuer string
// ClientID is this app's client id at the login server; every ID token
// must name it in aud (and in azp, when azp is present).
ClientID string
// ClientSecret authenticates the client with client_secret_basic. Leave
// it empty only together with WithClientAuth (PublicClient for none).
ClientSecret Secret
// AppURL is the app's public origin, scheme and host only
// ("https://admin.example.com"), as the browser sees it behind any
// proxy. The redirect URI is AppURL + Paths.Callback; the back-channel
// logout URI to register is AppURL + Paths.Backchannel. https, or http on
// a loopback host.
AppURL string
// SessionSecret derives the key cookies are sealed with
// (NewSecretSealer): at least MinSecretSize random bytes, kept secret
// and the same on every instance. Leave it empty only together with
// WithSealer.
SessionSecret Secret
// PreviousSessionSecrets still open cookies sealed before a rotation;
// see NewSecretSealer.
PreviousSessionSecrets []Secret
}
Config is what every Client needs and has no safe default: which login server, which client, where the app lives, and the key its cookies are sealed with. Everything with a default is an Option.
type CookieOptions ¶
type CookieOptions struct {
// Name is the session cookie's name; empty is DefaultCookieName. Without
// Domain it must start with "__Host-"; with Domain, with "__Secure-",
// which is all the browser allows there. The flow cookie is Name with
// FlowCookieSuffix.
Name string
// Domain shares the cookie with subdomains ("example.com" for
// admin.example.com and api.example.com). Empty keeps it host-only.
Domain string
// SameSite is http.SameSiteLaxMode (the default, also for zero) or
// http.SameSiteStrictMode; None is refused. Under Strict the callback
// lands the browser through a same-site page rather than a redirect, or
// the browser would hold back the new cookie on the first request. The
// flow cookie is always Lax: the login server's redirect back is a
// cross-site navigation that Strict would strip it from.
SameSite http.SameSite
}
CookieOptions shape the session cookie. Secure, HttpOnly and Path=/ are not options: every cookie the package writes has them, because a session cookie readable by script or sent over plain http is a session anyone can take.
type Decision ¶
type Decision int
Decision is an Authorizer's answer. Its zero value is Deny, so an authorizer that forgets to decide refuses: the careless path is the safe one.
type Event ¶
type Event struct {
Kind EventKind
At time.Time
// SessionID and Subject identify the session, when there is one.
SessionID string
Subject string
// Reason is set for EventRefuse.
Reason Reason
// Count is the sessions a back-channel logout ended.
Count int
// Err is the cause of a refusal, a grace or a failed revocation
// (EventRevokeFailed), for the log.
Err error
}
Event is one thing an Observer is told. Fields that do not apply to the Kind are zero.
type EventKind ¶
type EventKind string
EventKind names what happened.
const ( // EventLogin: a callback completed and a session was written. EventLogin EventKind = "login" // EventRefresh: a re-check said yes (tokens rotated or not). EventRefresh EventKind = "refresh" // EventGrace: the login server could not be reached and the last "yes" // was used, within the outage grace. A run of these is an outage. EventGrace EventKind = "grace" // EventRefuse: a request or a callback was refused; Reason says why. EventRefuse EventKind = "refuse" // EventLogout: the person signed out through the logout route. EventLogout EventKind = "logout" // EventBackchannelLogout: a logout token ended Count sessions. EventBackchannelLogout EventKind = "backchannel_logout" // EventRevokeFailed: sign-out could not revoke the session's refresh // token at the login server (Err says why: an error, or a server that // publishes no revocation endpoint). It comes just before the // EventLogout of the same sign-out, which still happened; a copy of // the cookie saved before it can keep refreshing until the server // refuses that token, so a run of these deserves an alert. A kind of // its own (rather than Err on EventLogout) lets an observer alert on // it without inspecting every logout, and matches the TypeScript // client's "revoke_failed". EventRevokeFailed EventKind = "revoke_failed" )
type Identity ¶
type Identity struct {
// Issuer and Subject together name the person at the login server. They
// key back-channel logout, so no mapper may change them on a User.
Issuer string
Subject string
Email string
// EmailVerified is true only for the boolean true or the string "true".
EmailVerified bool
Name string
// ProviderSessionID is the ID token's sid: the login server's session,
// which a back-channel logout token names. Empty when the server sends
// none (Google does not).
ProviderSessionID string
// Claims are every member of the ID token, the ones above included.
Claims Claims
}
Identity is who the login server says signed in: the verified ID token's claims, read once. Only the package builds one, after every floor check passed (signature, alg, iss, aud, exp, azp, nonce at sign-in, the same sub and iss at refresh), so a UserMapper can trust every field.
type IntrospectRequest ¶
type IntrospectRequest struct {
Token Secret
Hint TokenTypeHint
}
IntrospectRequest is an RFC 7662 introspection.
type Introspection ¶
type Introspection struct {
Active bool `json:"active"`
Subject string `json:"sub,omitempty"`
ClientID string `json:"client_id,omitempty"`
Scope string `json:"scope,omitempty"`
TokenType string `json:"token_type,omitempty"`
Issuer string `json:"iss,omitempty"`
Audience []string `json:"-"`
ExpiresAt time.Time `json:"-"`
IssuedAt time.Time `json:"-"`
// Claims are every member of the answer, the ones above included.
Claims Claims `json:"-"`
}
Introspection is the introspection endpoint's answer (RFC 7662 section 2.2), under the member names ubgo/auth's provider and others send. Active false is the server's "no", not an error.
type Lifetimes ¶
Lifetimes bound a session, whatever the login server says. Idle ends a session nobody used for that long (sliding: every active minute moves it); Absolute ends it that long after sign-in, used or not. A zero field takes its default; New refuses a negative one, or Idle above Absolute.
type LogoutTarget ¶
LogoutTarget names the sessions a back-channel logout token ends: those of Subject at Issuer, narrowed to the login server's session ProviderSessionID when the token names one (a sign-out of one browser at the server). At least one of Subject and ProviderSessionID is set; Issuer always is.
func (LogoutTarget) Matches ¶
func (t LogoutTarget) Matches(s Session) bool
Matches reports whether s is one of the sessions t names: same issuer, and the same subject and provider session for each of the two that t sets. It is the rule every SessionRevoker applies, exported so a custom store's query and the in-memory store cannot drift.
type MapReason ¶
type MapReason string
MapReason says why a UserMapper is called.
const ( // MapSignIn is the callback of a sign-in: the first time this session // sees the Identity. A mapper that creates the app's user does it here. MapSignIn MapReason = "sign_in" // MapRefresh is a re-check that brought a new ID token (a refresh at a // server that issues one), so roles derived from claims stay current. // Previous is set. MapRefresh MapReason = "refresh" )
type MapUserRequest ¶
type MapUserRequest struct {
Reason MapReason
Identity Identity
// Previous is the User stored in the session before a MapRefresh; nil
// at MapSignIn.
Previous *User
// AccessToken is the session's current access token, for a mapper that
// calls the userinfo endpoint (Provider.UserInfo) or an API of the login
// server.
AccessToken Secret
// Provider calls the login server with the client's credentials.
Provider *Provider
}
MapUserRequest is what a UserMapper decides from. A struct, so fields can be added without breaking mappers.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is the store NewMemoryStore returns. Its zero value is not usable; build it with NewMemoryStore.
func NewMemoryStore ¶
func NewMemoryStore() *MemoryStore
NewMemoryStore returns a server-side SessionStore and SessionRevoker that keeps sessions in this process's memory: the cookie carries only the session ID. It supports back-channel logout, and suits tests and a single instance; sessions are lost on restart and not shared between instances, for which a Redis or SQL store implements the same two interfaces. Expired sessions are dropped as they are read and swept periodically, so memory does not grow without bound.
Expiry is by the wall clock (time.Now), not by a Client's WithClock: the Client applies the Lifetimes itself on every request, so the store's expiry only bounds memory.
func (*MemoryStore) Delete ¶
func (m *MemoryStore) Delete(_ context.Context, s Session) error
Delete forgets s.
func (*MemoryStore) RevokeSessions ¶
func (m *MemoryStore) RevokeSessions(_ context.Context, t LogoutTarget) (int, error)
RevokeSessions forgets every session t matches.
type Observer ¶
Observer is told about logins, re-checks, refusals and logouts: the seam for metrics, audit logs and alerts. It cannot change a decision; it is called after the decision, synchronously, so it must return quickly and hand slow work to its own goroutine.
type ObserverFunc ¶
ObserverFunc adapts a function to Observer.
type Option ¶
type Option func(*settings)
Option sets one policy of a Client. Options run in order inside New; a mistake an option can only find while it runs (a nil value, a reserved parameter) is collected and returned by New, naming the option.
func WithAuthParams ¶
WithAuthParams adds parameters to every authorization request: prompt, login_hint, acr_values, hd, or Google's access_type=offline. A reserved parameter (state, nonce, code_challenge, redirect_uri and the other protocol parameters) is refused by New.
func WithAuthorizer ¶
func WithAuthorizer(a Authorizer) Option
WithAuthorizer adds the app's own rule, run on every request after the session is known to be fresh. The default is none.
Example ¶
An Authorizer adds the app's own rule to the login server's: here, the /admin area needs the admin role. Its zero answer is Deny, and an error refuses even with Allow.
package main
import (
"context"
"log"
"os"
"slices"
"strings"
"github.com/ubgo/auth/oidcclient"
)
// roleAdmin is the role the admin area requires.
const roleAdmin = "admin"
func main() {
authorize := func(_ context.Context, in oidcclient.AuthorizeRequest) (oidcclient.Decision, error) {
if strings.HasPrefix(in.Request.URL.Path, "/admin/") && !slices.Contains(in.User.Roles, roleAdmin) {
return oidcclient.Deny, nil
}
return oidcclient.Allow, nil
}
_, err := oidcclient.New(exampleConfig(), oidcclient.WithAuthorizer(authorize))
if err != nil {
log.Fatal(err)
}
}
// exampleConfig is the Config the examples share.
func exampleConfig() oidcclient.Config {
return oidcclient.Config{
Issuer: "https://login.example.com", ClientID: "oac_admin", AppURL: "https://admin.example.com",
ClientSecret: oidcclient.Secret(os.Getenv("OIDC_CLIENT_SECRET")), SessionSecret: oidcclient.Secret(os.Getenv("SESSION_SECRET")),
}
}
Output:
func WithClientAuth ¶
func WithClientAuth(a ClientAuth) Option
WithClientAuth authenticates the client with a instead of client_secret_basic: ClientSecretPost, PublicClient, or the app's own. New refuses it together with Config.ClientSecret.
func WithClock ¶
WithClock reads the time from now instead of time.Now, for tests of lifetimes, re-checks and grace. It is also the clock ID token expiry is checked against.
func WithCookie ¶
func WithCookie(o CookieOptions) Option
WithCookie sets the session cookie's name, domain and SameSite mode; New checks them against the browser's cookie-prefix rules.
func WithDiscovery ¶
func WithDiscovery(m ProviderMetadata) Option
WithDiscovery uses m instead of fetching the discovery document: a server without discovery, or a test. m is held to the same checks as a fetched document.
func WithHTTPClient ¶
WithHTTPClient sends every request to the login server through c: a proxy, mTLS, a test transport. The package uses a copy of c that never follows redirects, because an endpoint answering with a redirect could send the client's credentials elsewhere. The default times out after 10 seconds.
func WithLifetimes ¶
WithLifetimes sets the idle and absolute session lifetimes. A zero field keeps its default.
func WithLogger ¶
WithLogger logs to l instead of slog.Default(). Secrets are never logged; failures are logged with their cause.
func WithObserver ¶
WithObserver reports logins, re-checks, refusals and logouts to o.
func WithOutageGrace ¶
WithOutageGrace sets how long the last "yes" stands while the login server cannot be reached, counted from Session.CheckedAt. NoOutageGrace (zero) refuses at once; a negative d is refused. The default is DefaultOutageGrace. It never extends a session past its Lifetimes.
Example ¶
A strict outage policy: ask the login server on every request, and refuse as soon as it cannot be reached instead of trusting the last "yes" for five minutes.
package main
import (
"context"
"log"
"os"
"github.com/ubgo/auth/oidcclient"
)
func main() {
_, err := oidcclient.New(exampleConfig(),
oidcclient.WithRecheckInterval(oidcclient.RecheckEveryRequest),
oidcclient.WithOutageGrace(oidcclient.NoOutageGrace),
oidcclient.WithObserver(oidcclient.ObserverFunc(func(_ context.Context, e oidcclient.Event) {
if e.Kind == oidcclient.EventRefuse && e.Reason == oidcclient.ReasonServerDown {
log.Printf("login server unreachable: %v", e.Err)
}
})),
)
if err != nil {
log.Fatal(err)
}
}
// exampleConfig is the Config the examples share.
func exampleConfig() oidcclient.Config {
return oidcclient.Config{
Issuer: "https://login.example.com", ClientID: "oac_admin", AppURL: "https://admin.example.com",
ClientSecret: oidcclient.Secret(os.Getenv("OIDC_CLIENT_SECRET")), SessionSecret: oidcclient.Secret(os.Getenv("SESSION_SECRET")),
}
}
Output:
func WithPostLogoutPath ¶
WithPostLogoutPath is where the browser lands after sign-out: sent to the login server as post_logout_redirect_uri (Config.AppURL + path, which must be registered there), or redirected to directly when the server has no end-session endpoint. It must be a same-site path; the default is "/".
func WithRecheckInterval ¶
WithRecheckInterval sets how long the login server's last "yes" stands: the longest a person removed at the server can still use the app. RecheckEveryRequest (zero) asks on every request; a negative d is refused. The default is DefaultRecheckInterval.
func WithRechecker ¶
WithRechecker sets how the login server is asked again: RecheckByRefresh (the default), RecheckByIntrospection, RecheckByUserInfo, RecheckBackchannelOnly, or the app's own.
func WithResponder ¶
WithResponder answers refused requests with r instead of DefaultResponder.
func WithReturnPolicy ¶
func WithReturnPolicy(p ReturnPolicy) Option
WithReturnPolicy picks where sign-in lands: ReturnToRequested (the default), ReturnToFixed, ReturnToAllowed, or the app's own. Its answer is still held to the same-site path floor.
func WithScopes ¶
WithScopes replaces the requested scopes. "openid" is added when absent.
func WithSealer ¶
WithSealer seals cookies with sl (a KMS-backed sealer, auth.RingSealer) instead of the one derived from Config.SessionSecret. New refuses both at once: two sources of the key would leave it unclear which one opens yesterday's cookies.
func WithSessionStore ¶
func WithSessionStore(st SessionStore) Option
WithSessionStore keeps sessions in st instead of the stateless CookieStore: NewMemoryStore, or a Redis, SQL or app-owned store. A store that also implements SessionRevoker enables back-channel logout.
Example ¶
A custom SessionStore keeps sessions on the server, so the cookie carries only a sealed session ID and a back-channel logout can end a session the browser still holds.
package main
import (
"context"
"encoding/json"
"log"
"os"
"sync"
"github.com/ubgo/auth/oidcclient"
)
// kvStore is a server-side SessionStore in the shape a Redis or SQL store
// takes: the session is kept under its ID, the cookie carries only the ID,
// and SessionRevoker finds sessions by subject or provider session for
// back-channel logout. A map stands in for the database here.
type kvStore struct {
mu sync.Mutex
rows map[string][]byte
}
func (s *kvStore) Save(_ context.Context, sess oidcclient.Session) ([]byte, error) {
b, err := json.Marshal(sess)
if err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
s.rows[sess.ID] = b
return []byte(sess.ID), nil
}
func (s *kvStore) Load(_ context.Context, cookieValue []byte) (oidcclient.Session, error) {
s.mu.Lock()
b, ok := s.rows[string(cookieValue)]
s.mu.Unlock()
if !ok {
return oidcclient.Session{}, oidcclient.ErrNoSession
}
var sess oidcclient.Session
return sess, json.Unmarshal(b, &sess)
}
func (s *kvStore) Delete(_ context.Context, sess oidcclient.Session) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.rows, sess.ID)
return nil
}
func (s *kvStore) RevokeSessions(_ context.Context, t oidcclient.LogoutTarget) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
n := 0
for id, b := range s.rows {
var sess oidcclient.Session
if json.Unmarshal(b, &sess) == nil && t.Matches(sess) {
delete(s.rows, id)
n++
}
}
return n, nil
}
func main() {
_, err := oidcclient.New(exampleConfig(), oidcclient.WithSessionStore(&kvStore{rows: map[string][]byte{}}))
if err != nil {
log.Fatal(err)
}
}
// exampleConfig is the Config the examples share.
func exampleConfig() oidcclient.Config {
return oidcclient.Config{
Issuer: "https://login.example.com", ClientID: "oac_admin", AppURL: "https://admin.example.com",
ClientSecret: oidcclient.Secret(os.Getenv("OIDC_CLIENT_SECRET")), SessionSecret: oidcclient.Secret(os.Getenv("SESSION_SECRET")),
}
}
Output:
func WithUserMapper ¶
func WithUserMapper(m UserMapper) Option
WithUserMapper maps the verified Identity to the app's User at sign-in and at every refresh that brings a new ID token (the "OnLogin" hook). The default is DefaultUser.
Example ¶
The OnLogin hook: refuse an unverified email, link the login server's person to the app's own user (created on first sign-in), and take roles from the groups claim. Claims are dropped once read, to keep the cookie small. It runs again on every refresh that brings a new ID token, so a group removed at the server is a role removed here.
package main
import (
"context"
"crypto/rand"
"log"
"os"
"sync"
"github.com/ubgo/auth/oidcclient"
)
// appUsers stands in for the app's own user table.
type appUsers struct {
mu sync.Mutex
byID map[string]string
}
// findOrCreate returns the app user id linked to the login server's
// person, creating the row on first sign-in.
func (a *appUsers) findOrCreate(_ context.Context, iss, sub string) (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
key := iss + " " + sub
if id, ok := a.byID[key]; ok {
return id, nil
}
id := rand.Text()
a.byID[key] = id
return id, nil
}
func main() {
users := &appUsers{byID: map[string]string{}}
mapUser := func(ctx context.Context, in oidcclient.MapUserRequest) (oidcclient.User, error) {
if !in.Identity.EmailVerified {
return oidcclient.User{}, oidcclient.ErrAccessDenied
}
u := oidcclient.DefaultUser(in.Identity)
id, err := users.findOrCreate(ctx, u.Issuer, u.Subject)
if err != nil {
return oidcclient.User{}, err // a failure, not a "no": the person sees an error page and may retry
}
u.ID = id
u.Roles, _ = in.Identity.Claims.Strings("groups")
u.Claims = nil
return u, nil
}
_, err := oidcclient.New(exampleConfig(), oidcclient.WithUserMapper(mapUser))
if err != nil {
log.Fatal(err)
}
}
// exampleConfig is the Config the examples share.
func exampleConfig() oidcclient.Config {
return oidcclient.Config{
Issuer: "https://login.example.com", ClientID: "oac_admin", AppURL: "https://admin.example.com",
ClientSecret: oidcclient.Secret(os.Getenv("OIDC_CLIENT_SECRET")), SessionSecret: oidcclient.Secret(os.Getenv("SESSION_SECRET")),
}
}
Output:
type Paths ¶
Paths are where the four routes are served, each an absolute path on the app's origin. Client.Handler serves exactly these; an app that mounts the handlers one by one (LoginHandler and the others) sets Paths to where it mounted them, because the middleware redirects to Login, the redirect URI sent to the server is Config.AppURL + Callback, and the back-channel logout URI to register is Config.AppURL + Backchannel.
func PathsUnder ¶
PathsUnder returns the four routes under prefix ("/sso" gives /sso/login and so on). A trailing slash on prefix is dropped.
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider calls the login server as this client: the discovery document, the token, introspection and userinfo endpoints, each with the client's ClientAuth and HTTP client. The package's own flows use it, a Rechecker gets it, and Client.Provider returns it for anything else.
Every method applies the floors itself (an ID token from a refresh is verified and must name the session's iss and sub), and classifies every failure: ErrProviderRefused for the server's "no", ErrProviderUnavailable for no answer.
func (*Provider) Introspect ¶
func (p *Provider) Introspect(ctx context.Context, in IntrospectRequest) (Introspection, error)
Introspect asks the introspection endpoint about a token. A server without one is ErrInvalidConfig at the first call (New cannot know before discovery).
func (*Provider) Metadata ¶
func (p *Provider) Metadata(ctx context.Context) (ProviderMetadata, error)
Metadata returns the discovery document, fetching it on the first call and again, at most once a minute, after a failure. A failure is ErrProviderUnavailable (no answer) or ErrInvalidConfig (a document that names another issuer, or an endpoint that is not https).
func (*Provider) Refresh ¶
Refresh redeems a refresh token. The answer's ID token, when there is one, is verified as at sign-in (except the nonce, which a refresh does not carry) and must name in.Subject. invalid_grant is ErrProviderRefused.
func (*Provider) UserInfo ¶
func (p *Provider) UserInfo(ctx context.Context, accessToken Secret, subject string) (Claims, error)
UserInfo calls the userinfo endpoint with an access token. 401 is ErrProviderRefused. The answer's sub must equal subject, or it is refused (OpenID Connect Core section 5.3.2).
type ProviderMetadata ¶
type ProviderMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
JWKSURI string `json:"jwks_uri"`
UserInfoEndpoint string `json:"userinfo_endpoint,omitempty"`
// EndSessionEndpoint is RP-Initiated Logout's; without one (Google),
// sign-out ends the app's session only.
EndSessionEndpoint string `json:"end_session_endpoint,omitempty"`
IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
// CodeChallengeMethodsSupported, when listed, must include S256; S256 is
// sent whether listed or not (some servers support PKCE without saying).
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
// IDTokenSigningAlgValuesSupported is informational: the accepted
// algorithms are the package's fixed set, whatever the server lists.
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported,omitempty"`
// IssParameterSupported (RFC 9207) makes the callback require an iss
// parameter equal to the issuer; without it an iss sent is still checked.
IssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`
BackchannelLogoutSupported bool `json:"backchannel_logout_supported,omitempty"`
BackchannelLogoutSessionSupported bool `json:"backchannel_logout_session_supported,omitempty"`
}
ProviderMetadata is the part of the login server's discovery document (OpenID Connect Discovery 1.0, RFC 8414) the package reads, under the member names the server publishes. It is fetched from Issuer/.well-known/openid-configuration on first use and cached, or given once with WithDiscovery for a server without discovery or a test.
Whichever way it arrives, Issuer must equal Config.Issuer (a trailing slash aside) and every endpoint must be https (http on a loopback host), or sign-in fails: a document naming another issuer is the mix-up attack.
type Reason ¶
type Reason string
Reason is why a request was refused, for observers and logs. It is finer than RefusalKind and may grow; a Responder decides on Kind.
const ( ReasonNoSession Reason = "no_session" // no cookie, or one that does not open ReasonIdleExpired Reason = "idle_expired" // past LastSeenAt + Idle ReasonAbsoluteExpired Reason = "absolute_expired" // past CreatedAt + Absolute ReasonServerRefused Reason = "server_refused" // the Rechecker said Deny ReasonServerDown Reason = "server_down" // unreachable past the outage grace ReasonNotAuthorized Reason = "not_authorized" // the Authorizer or UserMapper said no ReasonProviderDenied Reason = "provider_denied" // the callback carried error=access_denied ReasonBadCallback Reason = "bad_callback" // state, PKCE, ID token or iss check failed ReasonHookFailed Reason = "hook_failed" // a UserMapper or Authorizer returned another error ReasonStoreFailed Reason = "store_failed" // the SessionStore or Sealer failed ReasonBackchannel Reason = "backchannel_logout" // a logout token ended the session ReasonProviderInvalid Reason = "provider_invalid" // the discovery document or a server answer broke a floor )
type RecheckRequest ¶
RecheckRequest is one re-check of a session whose last "yes" is older than the recheck interval.
type RecheckResult ¶
type RecheckResult struct {
// Decision is Allow when the login server still accepts the session.
Decision Decision
// Refreshed carries new tokens (and a new Identity, which the UserMapper
// sees as MapRefresh) when the check rotated them; nil otherwise. Only
// Provider.Refresh makes one.
Refreshed *Refreshed
}
RecheckResult is a Rechecker's answer. Its zero value is Deny.
type Rechecker ¶
type Rechecker interface {
Recheck(ctx context.Context, in RecheckRequest) (RecheckResult, error)
}
Rechecker asks the login server whether a session still stands. The package calls it at most once per recheck interval per session, and at most once at a time per session in this process: concurrent requests of one session wait for the same call (single-flight), so two tabs never spend one refresh token twice from here.
It fails closed: only (Allow, nil) keeps the session. Deny ends it and the person signs in again (the login server then decides). An error wrapping ErrProviderUnavailable keeps the last "yes" for the outage grace; any other error ends the session as Deny does.
func RecheckBackchannelOnly ¶
func RecheckBackchannelOnly() Rechecker
RecheckBackchannelOnly never calls the login server: the session stands until the server's back-channel logout token ends it (or a lifetime does). New refuses it unless the SessionStore implements SessionRevoker, because with a stateless cookie nothing could ever end the session. It trusts delivery that the specification makes best effort with no retry, so prefer a periodic re-check where removal must be certain.
func RecheckByIntrospection ¶
func RecheckByIntrospection() Rechecker
RecheckByIntrospection asks the introspection endpoint about the session's refresh token (its access token when it has none) and allows while it is active. Nothing is rotated, so a server whose refresh token rotation is costly is asked without it; whether a removed person shows as inactive depends on the server revoking their tokens (ubgo/auth's operator revoke does).
func RecheckByRefresh ¶
func RecheckByRefresh() Rechecker
RecheckByRefresh is the default Rechecker: redeem the session's refresh token. A server that re-asks its access rule on every refresh (ubgo/auth's provider does) refuses a removed person within one recheck interval. A session without a refresh token (the server granted none: ask for offline_access, or Google's access_type=offline through WithAuthParams) is refused at its first re-check, which New cannot know in advance and the log says.
func RecheckByUserInfo ¶
func RecheckByUserInfo() Rechecker
RecheckByUserInfo calls the userinfo endpoint with the session's access token, refreshing it first when it has expired, and allows on a 200 for the same subject. It suits a server whose userinfo, not its token endpoint, applies the access rule.
type RecheckerFunc ¶
type RecheckerFunc func(ctx context.Context, in RecheckRequest) (RecheckResult, error)
RecheckerFunc adapts a function to Rechecker.
func (RecheckerFunc) Recheck ¶
func (f RecheckerFunc) Recheck(ctx context.Context, in RecheckRequest) (RecheckResult, error)
Recheck calls f.
type RefreshRequest ¶
type RefreshRequest struct {
RefreshToken Secret
// Subject is the session's sub, required: an ID token in the answer
// must name it, so a refresh can never switch the session to another
// person. Empty is ErrInvalidConfig.
Subject string
}
RefreshRequest is a refresh-token grant for one session.
type Refreshed ¶
type Refreshed struct {
// contains filtered or unexported fields
}
Refreshed is a successful refresh: the new tokens and, when the server issued a new ID token, the Identity it verified. Its fields are unexported so that only Provider.Refresh makes one: a Rechecker can hand the package new tokens only by actually refreshing them, never by building a value with an unverified ID token.
type Refusal ¶
type Refusal struct {
Kind RefusalKind
Reason Reason
// LoginURL is the login route with this request's same-site path as
// return_to, set for RefusalLoginRequired.
LoginURL string
// Err is the cause, for the log. A Responder must not show it: it may
// name internals.
Err error
}
Refusal is one refused request, for a Responder to answer.
type RefusalKind ¶
type RefusalKind string
RefusalKind is what the person must be told: the answer a Responder writes. It is the coarse half of a Refusal; Reason is the fine half.
const ( // RefusalLoginRequired: no usable session. A page is redirected to // LoginURL; an API call gets 401. RefusalLoginRequired RefusalKind = "login_required" // RefusalNoAccess: signed in, but the app (Authorizer, UserMapper) or the // login server (access_denied at the callback) says no. 403. RefusalNoAccess RefusalKind = "no_access" // than the outage grace. The session is kept. 503. RefusalUnavailable RefusalKind = "unavailable" // RefusalFailed: something broke (a store, a hook's own failure, a // callback that does not verify). 500 for a failure of the app, 400 for // a callback that is not acceptable; the cause is logged, never shown. RefusalFailed RefusalKind = "failed" )
type Responder ¶
type Responder interface {
Respond(w http.ResponseWriter, r *http.Request, ref Refusal)
}
Responder writes the answer to a refused request: the seam for the app's own templates, a JSON shape its SPA expects, or translated pages. The default is DefaultResponder. It cannot change the decision: the request is refused whatever it writes.
func DefaultResponder ¶
func DefaultResponder() Responder
DefaultResponder answers a page request (IsPageRequest) with a redirect to the login route for RefusalLoginRequired and a plain HTML page for the rest, and an API call with a JSON body {"error": kind, "login_url": …} and the status of the kind. A custom Responder can delegate the kinds it does not handle to it.
type ResponderFunc ¶
type ResponderFunc func(w http.ResponseWriter, r *http.Request, ref Refusal)
ResponderFunc adapts a function to Responder.
func (ResponderFunc) Respond ¶
func (f ResponderFunc) Respond(w http.ResponseWriter, r *http.Request, ref Refusal)
Respond calls f.
type ReturnPolicy ¶
type ReturnPolicy func(in ReturnRequest) string
ReturnPolicy picks where the browser lands after sign-in. Whatever it returns is checked again: anything but a same-site path ("/x", not "//x", no backslash or line break, no scheme) is replaced by "/". So a policy can narrow the destination but never turn the login route into an open redirect.
func ReturnToAllowed ¶
func ReturnToAllowed(paths ...string) ReturnPolicy
ReturnToAllowed lands on the requested path when its path part (before any query) is one of paths, else on the first of paths.
Example ¶
ReturnToAllowed lands sign-ins only on listed pages; anything else goes to the first. Whatever a policy answers is still held to the same-site floor, so a policy can narrow the landing page but never open a redirect.
package main
import (
"fmt"
"github.com/ubgo/auth/oidcclient"
)
func main() {
policy := oidcclient.ReturnToAllowed("/dashboard", "/reports")
for _, requested := range []string{"/reports?month=11", "/admin", "//evil.example"} {
fmt.Println(policy(oidcclient.ReturnRequest{Requested: requested}))
}
}
Output: /reports?month=11 /dashboard /dashboard
func ReturnToFixed ¶
func ReturnToFixed(path string) ReturnPolicy
ReturnToFixed always lands on path, whatever was requested.
func ReturnToRequested ¶
func ReturnToRequested() ReturnPolicy
ReturnToRequested is the default ReturnPolicy: the path the person came from.
type ReturnRequest ¶
type ReturnRequest struct {
// Requested is the return_to the login route received, possibly empty
// or hostile.
Requested string
Request *http.Request
}
ReturnRequest is what a ReturnPolicy decides from.
type Sealer ¶
type Sealer interface {
Seal(ctx context.Context, plain []byte, aad string) (string, error)
Open(ctx context.Context, sealed, aad string) ([]byte, error)
}
Sealer encrypts what the package puts in cookies (the session under the default store, the session id under a server-side one, and the sign-in flow's state, nonce and PKCE verifier) and opens it again. It is the seam for keys that live in a KMS or HSM (Vault transit, AWS KMS) and for an app that already has a sealer.
The method set is the same as github.com/ubgo/auth's Sealer, so a value of that type (auth.RingSealer) is accepted as is, without this module importing the core.
aad is the cookie's name: Open must refuse a value sealed under another aad, so a flow cookie can never be replayed as a session cookie. Open answers ErrSealedCorrupt (or an error wrapping it) for a value that does not open, which reads as "no session" (the person signs in again); any other error is a failure to reach the key service, answered as a failure (ReasonStoreFailed), never as an empty session. A Sealer that rotates keys puts its key id inside the sealed text; the built-in one tries each key.
func NewSecretSealer ¶
NewSecretSealer is the default Sealer: AES-256-GCM under a key derived from current with HKDF-SHA256, with the cookie name as associated data. current seals; current and every previous secret open, newest first, so a secret is rotated without signing anyone out: put the new secret first and the old one in previous, deploy, and drop the old one once the longest session lifetime has passed. Each secret is at least MinSecretSize bytes.
type Secret ¶
type Secret string
Secret is a credential the package holds: the client secret, an access, refresh or ID token. It formats as "[redacted]" under every fmt verb and in slog, so a session or a config printed while debugging leaks nothing. Reveal is the one way to read it, which makes every use greppable.
It marshals to JSON as its plain value on purpose: a SessionStore serialises sessions to keep them, and the stored form is sealed (cookie store) or kept server side. Never JSON-encode a Session into a log.
type Session ¶
type Session struct {
// ID is random (256 bits), set at sign-in and stable for the session's
// life. It is the server-side store's key and the single-flight key that
// lets one refresh serve every concurrent request of the session.
ID string `json:"id"`
User User `json:"user"`
// ProviderSessionID is the ID token's sid, which a back-channel logout
// token may name instead of the subject.
ProviderSessionID string `json:"sid,omitempty"`
Tokens Tokens `json:"tokens"`
// CreatedAt is the sign-in; the absolute lifetime counts from it.
CreatedAt time.Time `json:"created_at"`
// LastSeenAt is the last request that moved the idle window; the idle
// lifetime counts from it. It advances at most once a minute, so a busy
// session does not rewrite its cookie or row on every request.
LastSeenAt time.Time `json:"last_seen_at"`
// CheckedAt is the last time the login server said yes. The session is
// fresh while now is within the recheck interval of it, and the outage
// grace counts from it.
CheckedAt time.Time `json:"checked_at"`
// ExpiresAt is the earlier of LastSeenAt+Idle and CreatedAt+Absolute,
// written by the package before every Save, so a store can set its TTL
// from it without knowing the Lifetimes.
ExpiresAt time.Time `json:"expires_at"`
}
Session is one signed-in browser: who, the tokens, and the three times the model runs on. The package writes every field; a SessionStore only keeps and returns it, unchanged.
type SessionRevoker ¶
type SessionRevoker interface {
// RevokeSessions ends every session matching t and returns how many it
// ended. Zero matches is not an error.
RevokeSessions(ctx context.Context, t LogoutTarget) (int, error)
}
SessionRevoker is the optional upgrade a server-side SessionStore implements to find and end sessions without their cookie: what back-channel logout and RecheckBackchannelOnly need. New refuses RecheckBackchannelOnly with a store that lacks it, and the back-channel route answers ErrBackchannelUnsupported.
type SessionStore ¶
type SessionStore interface {
// Save keeps s until s.ExpiresAt and returns the bytes the cookie
// carries. It is called at sign-in and whenever a field changed.
Save(ctx context.Context, s Session) (cookieValue []byte, err error)
// Load returns the session cookieValue names, or ErrNoSession when none
// is live. Any other error is a failure and refuses the request.
Load(ctx context.Context, cookieValue []byte) (Session, error)
// Delete ends s (sign-out, expiry, a refused re-check). Deleting a
// session that is already gone is not an error.
Delete(ctx context.Context, s Session) error
}
SessionStore keeps sessions. The package owns the session cookie: it seals whatever bytes Save returns under the cookie name, sets the cookie with the CookieOptions, and hands the opened bytes back to Load. So a store never touches HTTP, cookies or keys, and every store gets the same cookie floors.
Two models fit: a stateless store returns the whole session as the cookie value (the default, CookieStore), a server-side store (Redis, SQL, the app's own session system reached through ctx) keeps the session and returns its ID. Only a server-side store can end a session the browser still holds a cookie for, which back-channel logout needs (SessionRevoker).
func CookieStore ¶
func CookieStore() SessionStore
CookieStore is the default SessionStore: stateless, the whole session JSON-encoded into the cookie (sealed by the Client, split over a few cookies when it exceeds one), nothing kept on the server. It survives restarts and needs no database, but cannot end a session the browser still holds, so it supports no back-channel logout: the recheck interval is what bounds a removed person's access.
type TokenTypeHint ¶
type TokenTypeHint string
TokenTypeHint is RFC 7009's token_type_hint.
const ( HintRefreshToken TokenTypeHint = "refresh_token" HintAccessToken TokenTypeHint = "access_token" )
type Tokens ¶
type Tokens struct {
AccessToken Secret `json:"access_token,omitempty"`
RefreshToken Secret `json:"refresh_token,omitempty"`
IDToken Secret `json:"id_token,omitempty"`
// AccessExpiresAt is when the access token stops, from expires_in; zero
// when the server sent none.
AccessExpiresAt time.Time `json:"access_expires_at,omitzero"`
// Scope is the granted scope, space separated, as the server sent it.
Scope string `json:"scope,omitempty"`
}
Tokens are what the login server's token endpoint returned, kept so the session can be re-checked (RefreshToken), the person signed out at the server (IDToken as id_token_hint) and the server's APIs called (AccessToken).
type User ¶
type User struct {
// ID is the app's id for the person. DefaultUser sets it to Subject; a
// mapper that links to the app's own user table sets that row's id.
ID string `json:"id"`
// Issuer and Subject are the Identity's and cannot be changed by a
// mapper: a User whose Issuer or Subject differ is refused (fail closed),
// because back-channel logout finds sessions by them.
Issuer string `json:"iss"`
Subject string `json:"sub"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name,omitempty"`
Roles []string `json:"roles,omitempty"`
Claims Claims `json:"claims,omitempty"`
}
User is the signed-in person as the app sees it: UserFrom returns it on every request the middleware let through. DefaultUser fills it from the Identity; a UserMapper replaces or enriches it (the app's own user id, roles from a groups claim).
It is stored in the session, so its size is the cookie's size under the default store: a mapper that does not need Claims may set it to nil.
func DefaultUser ¶
DefaultUser is the User the package stores when no UserMapper is set: every field copied from id, ID set to the Subject, no Roles. A mapper usually starts from it and changes what it needs.
type UserMapper ¶
type UserMapper func(ctx context.Context, in MapUserRequest) (User, error)
UserMapper turns a verified Identity into the app's User: link or create the app's own user, derive roles from claims, refuse an unverified email. It is the "OnLogin" hook. Returning ErrAccessDenied (or an error wrapping it) refuses with the no-access response; any other error refuses as a failure. Either way no session is written (MapSignIn) or the session ends (MapRefresh): a mapper error never lets anyone in.