Documentation
¶
Overview ¶
Package oidc provides HTTP middleware for browser-based, cookie-backed OIDC login sessions: the login/callback/logout flow, session cookie management, and transparent token refresh.
Index ¶
- Variables
- func AccessTokenFromContext(ctx context.Context) string
- func ContextWithAccessToken(ctx context.Context, token string) context.Context
- func ContextWithOIDCUserInfo(ctx context.Context, userInfo *goth.User) context.Context
- func UserInfoFromContext(ctx context.Context) *goth.User
- type BrowserConfig
- type CookieConfig
- type Handler
- func (h *Handler) AuthStart() http.HandlerFunc
- func (h *Handler) Callback() http.HandlerFunc
- func (h *Handler) CallbackPath() string
- func (h *Handler) LoginPath() string
- func (h *Handler) Logout() http.HandlerFunc
- func (h *Handler) LogoutPath() string
- func (h *Handler) WithBearerPassthrough(v bool) *Handler
- func (h *Handler) Wrap(next http.Handler) http.Handler
- type OIDCConfig
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( DefaultCookiePath = "/" DefaultTokenCookieName = "oidc_token" DefaultTokenCookieMaxAge = time.Hour DefaultStateCookieName = "oidc_state" DefaultStateCookieMaxAge = 5 * time.Minute DefaultRefreshCookieName = "oidc_refresh" DefaultRefreshCookieMaxAge = 24 * time.Hour DefaultTokenExpiryCookieName = "oidc_expires_in" // #nosec G101 DefaultIDTokenCookieName = "oidc_id_token" // #nosec G101 )
Default cookie names, paths, and max-ages used when OIDCConfig or CookieConfig leave the corresponding field unset.
Functions ¶
func AccessTokenFromContext ¶
AccessTokenFromContext returns the access token from the provided context, or "" if none is found.
func ContextWithAccessToken ¶
ContextWithAccessToken returns a new context with the provided access token.
func ContextWithOIDCUserInfo ¶
ContextWithOIDCUserInfo returns a new context with the provided OIDC user info.
Types ¶
type BrowserConfig ¶ added in v0.5.0
type BrowserConfig struct {
// Issuer is the OIDC issuer/discovery base URL.
Issuer string `json:"issuer" mapstructure:"issuer"`
// ClientID is the OAuth2/OIDC client identifier registered with the provider.
ClientID string `json:"client_id" mapstructure:"client-id"`
// ClientSecret is the confidential client secret used in code exchange.
ClientSecret string `json:"client_secret" mapstructure:"client-secret"`
// Scopes controls requested OAuth2 scopes; defaults to openid/profile/email when omitted.
Scopes []string `json:"scopes,omitzero" mapstructure:"scopes,omitzero"`
// RedirectURI is the absolute callback URL registered with the OIDC provider.
RedirectURI string `json:"redirect_uri" mapstructure:"redirect-uri"`
// LoginPath is the local route that initiates login; defaults to /auth/login.
LoginPath string `json:"login_path,omitzero" mapstructure:"login-path,omitzero"`
// CookieDomain sets the optional cookie domain attribute for session cookies.
CookieDomain string `json:"cookie_domain,omitzero" mapstructure:"cookie-domain,omitzero"`
// CookieSecure controls the cookie Secure attribute and must be true for authenticated flows.
CookieSecure bool `json:"cookie_secure,omitzero" mapstructure:"cookie-secure,omitzero"`
}
BrowserConfig is a shared configuration contract for interactive, browser-based OIDC login flows.
Use BrowserConfig when your server application needs to:
- redirect a human user to an OIDC provider login page,
- exchange an authorization code for tokens server-side, and
- keep the browser session in HTTP-only cookies.
Typical usage:
- call Validate to fail fast on insecure or incomplete configuration,
- call ToClientConfig to construct an oidc.Client, then
- call ToOIDCConfig to configure this package's middleware Handler.
BrowserConfig is intentionally focused on browser sessions. For machine-to-machine APIs or bearer-token-only validation, prefer JWT validator configuration instead of browser login middleware.
Example (AuthenticatedConsoleDefaults) ¶
package main
import (
"fmt"
oidcmw "github.com/dioad/auth/http/middleware/oidc"
)
func main() {
cfg := oidcmw.BrowserConfig{
Issuer: "https://auth.example.com/realms/connect",
ClientID: "connect-control-console",
ClientSecret: "super-secret",
RedirectURI: "https://control.example.com/auth/callback",
CookieSecure: true,
}
if err := cfg.Validate(); err != nil {
fmt.Println("invalid config")
return
}
clientCfg := cfg.ToClientConfig()
mwCfg := cfg.ToOIDCConfig()
fmt.Println(clientCfg.URL)
fmt.Println(mwCfg.LoginPath)
fmt.Println(mwCfg.Scopes)
fmt.Println(mwCfg.TokenCookie.Secure)
}
Output: https://auth.example.com/realms/connect /auth/login [openid profile email] true
Example (CustomLoginPathAndScopes) ¶
package main
import (
"fmt"
oidcmw "github.com/dioad/auth/http/middleware/oidc"
)
func main() {
cfg := oidcmw.BrowserConfig{
Issuer: "https://issuer.example",
ClientID: "admin-ui",
ClientSecret: "secret",
RedirectURI: "https://admin.example/auth/callback",
CookieSecure: true,
LoginPath: "/console/login",
Scopes: []string{"openid", "profile", "groups"},
}
mwCfg := cfg.ToOIDCConfig()
fmt.Println(mwCfg.LoginPath)
fmt.Println(mwCfg.Scopes)
}
Output: /console/login [openid profile groups]
func (BrowserConfig) ToClientConfig ¶ added in v0.5.0
func (c BrowserConfig) ToClientConfig() authoidc.ClientConfig
ToClientConfig converts BrowserConfig into oidc.ClientConfig used to build an OIDC client for authorization-code token exchange.
func (BrowserConfig) ToOIDCConfig ¶ added in v0.5.0
func (c BrowserConfig) ToOIDCConfig() OIDCConfig
ToOIDCConfig converts BrowserConfig into middleware OIDCConfig suitable for Handler.
Call Validate before using the converted configuration in production paths.
func (BrowserConfig) Validate ¶ added in v0.5.0
func (c BrowserConfig) Validate() error
Validate checks that BrowserConfig is suitable for authenticated browser OIDC flows and enforces secure-cookie sessions.
Example (InsecureCookieRejected) ¶
package main
import (
"fmt"
oidcmw "github.com/dioad/auth/http/middleware/oidc"
)
func main() {
cfg := oidcmw.BrowserConfig{
Issuer: "https://issuer.example",
ClientID: "admin-ui",
ClientSecret: "secret",
RedirectURI: "https://admin.example/auth/callback",
CookieSecure: false,
}
fmt.Println(cfg.Validate())
}
Output: cookie-secure must be true for authenticated browser OIDC
type CookieConfig ¶
type CookieConfig struct {
Name string `json:"name" mapstructure:"name"`
Domain string `json:"domain,omitzero" mapstructure:"domain,omitzero"`
Secure bool `json:"secure,omitzero" mapstructure:"secure,omitzero"`
Path string `json:"path,omitzero" mapstructure:"path,omitzero"`
MaxAge time.Duration `json:"max_age,omitzero" mapstructure:"max-age,omitzero"`
}
CookieConfig configures a single session cookie's name, scope, and lifetime.
func (CookieConfig) Cookie ¶
func (c CookieConfig) Cookie(value string) *http.Cookie
Cookie builds an *http.Cookie carrying value, using c's configured name, domain, path, and max-age.
func (CookieConfig) Delete ¶
func (c CookieConfig) Delete(w http.ResponseWriter)
Delete expires c's cookie on w.
func (CookieConfig) Set ¶
func (c CookieConfig) Set(w http.ResponseWriter, value string)
Set writes value to w as a cookie configured by c.
type Handler ¶
type Handler struct {
Client *oidc.Client
Config OIDCConfig
// contains filtered or unexported fields
}
Handler provides browser-based OIDC login middleware: the login/callback/logout flow, session cookie management, and transparent token refresh.
func NewHandler ¶
func NewHandler(client *oidc.Client, cfg OIDCConfig) *Handler
NewHandler creates a new OIDC login Handler, filling in cfg's defaults (login/logout paths, cookie names/paths/max-ages).
func (*Handler) AuthStart ¶
func (h *Handler) AuthStart() http.HandlerFunc
AuthStart initiates the OIDC authentication flow.
func (*Handler) Callback ¶
func (h *Handler) Callback() http.HandlerFunc
Callback handles the OIDC provider callback and sets cookies.
func (*Handler) CallbackPath ¶ added in v0.8.0
CallbackPath returns the URL path component of Config.RedirectURI that Callback should be registered at, or "" if RedirectURI is unset or unparseable.
func (*Handler) LoginPath ¶ added in v0.8.0
LoginPath returns the path AuthStart should be registered at.
func (*Handler) Logout ¶
func (h *Handler) Logout() http.HandlerFunc
Logout clears all authentication cookies and redirects to root.
func (*Handler) LogoutPath ¶ added in v0.8.0
LogoutPath returns the path Logout should be registered at.
func (*Handler) WithBearerPassthrough ¶ added in v0.8.0
WithBearerPassthrough configures whether Wrap forwards a request carrying a non-empty Authorization header to next without checking the OIDC session cookie, on the assumption a separately chained bearer-token validator (e.g. jwt.Handler) will authenticate that header itself. Defaults to false.
Only enable this when this Handler is explicitly chained ahead of another auth middleware that validates the Authorization header — never when it is used as a sole auth gate (e.g. via resolveOIDCHandler/WithServerAuth), since an unvalidated header would then let any request bypass authentication entirely.
type OIDCConfig ¶
type OIDCConfig struct {
Scopes []string `json:"scopes,omitzero" mapstructure:"scopes,omitzero"`
RedirectURI string `json:"redirect_uri,omitzero" mapstructure:"redirect-uri,omitzero"`
TokenCookie CookieConfig `json:"token_cookie,omitzero" mapstructure:"token-cookie,omitzero"`
StateCookie CookieConfig `json:"state_cookie,omitzero" mapstructure:"state-cookie,omitzero"`
RefreshCookie CookieConfig `json:"refresh_cookie,omitzero" mapstructure:"refresh-cookie,omitzero"`
TokenExpiryCookie CookieConfig `json:"token_expiry,omitzero" mapstructure:"token-expiry,omitzero"`
RedirectCookie CookieConfig `json:"redirect_cookie,omitzero" mapstructure:"redirect-cookie,omitzero"`
IDTokenCookie CookieConfig `json:"id_token_cookie,omitzero" mapstructure:"id-token-cookie,omitzero"`
RefreshWindow time.Duration `json:"refresh_window,omitzero" mapstructure:"refresh-window,omitzero"`
Now func() time.Time `json:"-" mapstructure:"-"`
LoginPath string `json:"login_path,omitzero" mapstructure:"login-path,omitzero"`
LogoutPath string `json:"logout_path,omitzero" mapstructure:"logout-path,omitzero"`
// AllowInsecureCookies disables the default Secure attribute on session
// cookies, allowing them to be sent over plain HTTP. Session cookies
// carry live OAuth access and refresh tokens, so this must only be set
// for local HTTP development — never in production. Mirrors
// oidc.ValidatorConfig.AllowInsecureHMAC's explicit-opt-in shape.
AllowInsecureCookies bool `json:"allow_insecure_cookies,omitzero" mapstructure:"allow-insecure-cookies,omitzero"`
}
OIDCConfig configures browser-based OIDC login: scopes, redirect URI, session cookies, refresh behavior, and login/logout paths.