Documentation
¶
Overview ¶
Package jawsauth provides OIDC and OAuth2 profile authentication for JaWS sessions.
OIDC mode uses discovery, PKCE, nonce and ID token verification. Profile mode uses explicit provider endpoints, PKCE and an authenticated profile response with an application-supplied subject extractor. The resulting claims are stored in a JaWS session. OIDC attempts refresh before expiry; profile auth expires after a bounded lifetime. Both modes support admin email gates.
Create a Server with New (or NewDebug) and protect handlers with Server.Wrap, Server.WrapAdmin, Server.Handler or Server.HandlerAdmin.
Index ¶
- Variables
- func DefaultSetHeaders(hw http.ResponseWriter, ishttps bool)
- type Config
- type EventFunc
- type FailedFunc
- type HandleFunc
- type JawsAuth
- type LinkFunc
- type OAuth2CallbackError
- type Server
- func (srv *Server) CurrentClaims(sess *jaws.Session) map[string]any
- func (srv *Server) GetAdmins() (emails []string)
- func (srv *Server) HandleAuthResponse(hw http.ResponseWriter, hr *http.Request)
- func (srv *Server) HandleLink(hw http.ResponseWriter, hr *http.Request)
- func (srv *Server) HandleLogin(hw http.ResponseWriter, hr *http.Request)
- func (srv *Server) HandleLogout(hw http.ResponseWriter, hr *http.Request)
- func (srv *Server) Handler(name string, dot any) http.Handler
- func (srv *Server) HandlerAdmin(name string, dot any) http.Handler
- func (srv *Server) IsAdmin(email string) (yes bool)
- func (srv *Server) Logout(sess *jaws.Session, hr *http.Request) (cleared bool)
- func (srv *Server) Set403Handler(h http.Handler)
- func (srv *Server) SetAdmins(emails []string)
- func (srv *Server) Valid() bool
- func (srv *Server) Wrap(h http.Handler) (rh http.Handler)
- func (srv *Server) WrapAdmin(h http.Handler) (rh http.Handler)
Constants ¶
This section is empty.
Variables ¶
var ErrConfig errConfig
ErrConfig matches all configuration validation errors.
var ErrConfigEndpointMustBeHTTPS = errors.New("provider endpoint must use https")
ErrConfigEndpointMustBeHTTPS means a provider endpoint must use HTTPS, or HTTP when AllowInsecureIssuer is enabled.
var ErrConfigIssuerMustBeHTTPS = errors.New("issuer url must use https")
ErrConfigIssuerMustBeHTTPS means Issuer must use HTTPS, or HTTP when AllowInsecureIssuer is enabled.
var ErrConfigMissingValue = errors.New("config value is missing")
ErrConfigMissingValue means a required configuration value is missing.
var ErrConfigURLMissingHost = errors.New("url host is missing")
ErrConfigURLMissingHost means a configured URL does not include a host.
var ErrConfigURLNotAbsolute = errors.New("url is not absolute")
ErrConfigURLNotAbsolute means a configured URL is not absolute.
var ErrOAuth2Callback = errors.New("oauth2 callback error")
ErrOAuth2Callback matches OAuth2 callback errors.
Callback fields are untrusted browser input, even when they appear to come from the identity provider.
var ErrOAuth2ExpiredState = errors.New("oauth2 expired state")
ErrOAuth2ExpiredState means the provider returned after the flow lifetime.
var ErrOAuth2InvalidOrigin = errors.New("oauth2 invalid origin")
ErrOAuth2InvalidOrigin means a link start request failed the same-origin check.
var ErrOAuth2InvalidProfile = errors.New("oauth2 invalid profile")
ErrOAuth2InvalidProfile means the profile or access token could not prove a stable subject.
var ErrOAuth2LinkRejected = errors.New("oauth2 link rejected")
ErrOAuth2LinkRejected means the application did not accept a proven link.
var ErrOAuth2LoginInProgress = errors.New("oauth2 login already in progress")
ErrOAuth2LoginInProgress means a callback has consumed the pending login state.
var ErrOAuth2MissingPKCEVerifier = errors.New("oauth2 missing pkce verifier")
ErrOAuth2MissingPKCEVerifier means the callback session did not contain the required PKCE verifier.
var ErrOAuth2MissingSession = errors.New("oauth2 missing session")
ErrOAuth2MissingSession means the session or its pending flow is no longer usable.
var ErrOAuth2MissingState = errors.New("oauth2 missing state")
ErrOAuth2MissingState means the callback session did not contain the expected state value.
var ErrOAuth2NotConfigured = errors.New("oauth2 not configured")
ErrOAuth2NotConfigured means OAuth2/OIDC is not configured on the Server.
var ErrOAuth2WrongState = errors.New("oauth2 wrong state")
ErrOAuth2WrongState means the callback state value did not match the stored session state.
var ErrOIDCDiscovery = errors.New("oidc discovery failed")
ErrOIDCDiscovery means OIDC provider discovery failed.
var ErrOIDCInvalidIDToken = errors.New("oidc invalid id_token")
ErrOIDCInvalidIDToken means id_token verification failed.
var ErrOIDCMissingIDToken = errors.New("oidc missing id_token")
ErrOIDCMissingIDToken means the token response did not include an id_token.
var ErrOIDCMissingNonce = errors.New("oidc missing nonce")
ErrOIDCMissingNonce means the login request did not include a nonce.
var ErrOIDCNonceMismatch = errors.New("oidc nonce mismatch")
ErrOIDCNonceMismatch means the id_token nonce did not match the stored session nonce.
var ErrOIDCProviderMetadata = errors.New("oidc provider metadata invalid")
ErrOIDCProviderMetadata means discovered OIDC metadata was invalid.
var ErrServerNilJaws = errors.New("jawsauth: nil *jaws.Jaws")
ErrServerNilJaws is returned by New and NewDebug when the *jaws.Jaws argument is nil. Server methods dereference Server.Jaws and require it to be non-nil for the lifetime of the Server.
var ErrUserInfoInvalidResponse = errors.New("userinfo invalid response")
ErrUserInfoInvalidResponse means the UserInfo response was not one JSON object.
var ErrUserInfoStatus = errors.New("userinfo status")
ErrUserInfoStatus means the UserInfo endpoint returned a non-200 HTTP status.
var ErrUserInfoTooLarge = errors.New("userinfo response too large")
ErrUserInfoTooLarge means the authenticated profile exceeded the response limit.
var SetHeaders = DefaultSetHeaders
SetHeaders writes the HTTP response headers for all OAuth endpoint responses.
It defaults to DefaultSetHeaders and may be reassigned at startup to customize headers; it must not be reassigned concurrently with serving requests.
Functions ¶
func DefaultSetHeaders ¶ added in v1.0.7
func DefaultSetHeaders(hw http.ResponseWriter, ishttps bool)
DefaultSetHeaders writes response headers for OAuth endpoint responses.
Types ¶
type Config ¶
type Config struct {
RedirectURL string // required. e.g. "https://application.example.com/oauth2/callback"
Issuer string // required. e.g. "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/v2.0"
// Namespace isolates providers sharing one JaWS instance. New appends it to
// the four exported Server session-key fields; use a distinct value per provider.
Namespace string
AuthURL string
TokenURL string
UserInfoURL string
// AllowInsecureIssuer permits HTTP issuer and provider endpoints and is only for tests/dev.
AllowInsecureIssuer bool
// HTTPClient handles discovery, JWKS, token exchange/refresh and UserInfo.
// Requests cap its timeout at 15 seconds. Discovery/JWKS follow only HTTPS
// redirects unless AllowInsecureIssuer is set; token and UserInfo follow none.
// A request's oauth2.HTTPClient can override code exchange and UserInfo;
// background refresh uses HTTPClient.
HTTPClient *http.Client
Scopes []string // optional; OIDC adds "openid" and "email"; profile mode adds none
ClientID string
ClientSecret string
// ProfileSubject enables OAuth2 profile mode and returns a stable, non-empty
// subject from the authenticated profile. It may map provider verification
// data to claims["email_verified"] for admin checks. Profile JSON numbers
// arrive as json.Number.
ProfileSubject func(map[string]any) (string, error)
}
Config holds the OIDC/OAuth2 settings used by New and NewDebug to construct a Server.
RedirectURL, Issuer and ClientID are required. Setting ProfileSubject selects profile mode and requires AuthURL, TokenURL and UserInfoURL. Otherwise OIDC mode discovers endpoints; those three URLs may override them.
type EventFunc ¶ added in v0.3.0
EventFunc is called for login and logout lifecycle events.
jawsauth calls Server.LogoutEvent after releasing SessionRotationLock. When LoginEvent is set, clearing auth before it begins suppresses both events; clearing auth during it defers LogoutEvent until it returns. LogoutEvent receives a nil request for timer cleanup, deferred delivery, or a call to Server.Logout with a nil request. When re-login replaces existing auth, its LogoutEvent runs on the old session before the new sign-in is stored; calling Logout there cancels the new sign-in. For cross-provider cleanup, check the other Server's CurrentClaims before calling Logout on the old session; that call can revoke a running sign-in.
type FailedFunc ¶ added in v0.9.0
type FailedFunc func(hw http.ResponseWriter, hr *http.Request, httpCode int, err error, email string) (wroteresponse bool)
FailedFunc is called on callback failures and when a protected request meets a running login callback before session rotation. Other flow-start failures write their own response.
It returns true if it wrote the HTTP response itself, in which case jawsauth writes nothing further. Errors can contain untrusted browser-supplied text. Quote errors when logging them and escape them for the output format when rendering them.
type HandleFunc ¶
HandleFunc registers handler to serve requests for the given URI path.
It matches the shape of http.ServeMux.Handle and is supplied to New and NewDebug so the login, logout and callback endpoints can be wired into the caller's router.
type JawsAuth ¶ added in v0.6.0
type JawsAuth struct {
// contains filtered or unexported fields
}
JawsAuth exposes authenticated session data to JaWS templates. Its zero value is safe to use and reports no user data.
func (*JawsAuth) Data ¶ added in v0.6.0
Data returns the OIDC or OAuth2 profile claims stored in the session, or nil. It does not check expiry; use Server.CurrentClaims for access decisions. It is safe to call on a nil or zero-value JawsAuth.
func (*JawsAuth) Email ¶ added in v0.6.0
Email returns the email stored in the session, or an empty string.
The value is a parsed address with ASCII letters lowercased. It does not check expiry; use Server.CurrentClaims for access decisions. It is safe to call on a nil or zero-value JawsAuth.
func (*JawsAuth) EmailVerified ¶ added in v1.0.9
EmailVerified reports whether the session address came from a verified email claim.
Addresses taken from mail or public_email claims are unverified. It does not check expiry; use Server.CurrentClaims for access decisions. It is safe to call on a nil or zero-value JawsAuth.
func (*JawsAuth) IsAdmin ¶ added in v0.6.0
IsAdmin reports whether the stored session email is an administrator.
It applies Server.RequireVerifiedAdminEmail to non-empty admin lists. It does not check login expiry; use Server.CurrentClaims for access decisions. With an empty admin list, it can return true without a session. A nil or zero-value JawsAuth follows Server.IsAdmin's nil-server behavior and returns true.
type LinkFunc ¶ added in v1.5.0
type LinkFunc func(sess *jaws.Session, hr *http.Request, claims map[string]any) (statusCode int, err error)
LinkFunc receives the current session and a newly authenticated identity. Recheck the existing authentication before a durable link write; with multiple providers, use the original provider's CurrentClaims. Logout and flow cancellation affect only their own Server. jawsauth holds SessionRotationLock while calling LinkFunc; do not acquire it again or call Server.Logout in the callback. Claims contain raw provider fields, so their types (including email_verified) may differ from stored session values. Return zero and nil on success, or an HTTP error status.
type OAuth2CallbackError ¶ added in v1.0.0
type OAuth2CallbackError struct {
Code string // OAuth2 error code from the callback.
Description string // Optional error description from the callback.
URI string // Optional URI with details about the callback error.
}
OAuth2CallbackError describes an OAuth2 callback error response.
func (*OAuth2CallbackError) Error ¶ added in v1.0.0
func (err *OAuth2CallbackError) Error() string
func (*OAuth2CallbackError) Is ¶ added in v1.0.0
func (err *OAuth2CallbackError) Is(target error) bool
type Server ¶
type Server struct {
Jaws *jaws.Jaws
// New appends Config.Namespace to these four session keys when configured.
SessionKey string // default is "oidc_claims", value will be of type map[string]any
SessionTokenKey string // default is "oauth2_tokensource"; an oauth2.TokenSource in OIDC mode, unset in profile mode
SessionEmailKey string // default is "email", value is a parsed string address with ASCII letters lowercased
SessionEmailVerifiedKey string // default is "email_verified", value will be of type bool
HandledPaths map[string]struct{} // URI paths excluded from OAuth return targets
LoginEvent EventFunc // called after claims are stored; revocation may suppress or follow it
LogoutEvent EventFunc // auth-clear callback; see EventFunc for ordering and nil requests
LoginFailed FailedFunc // callback failures and protected requests during a login callback before rotation
LinkEvent LinkFunc // required by HandleLink; register its POST route separately
// SessionRotationLock is held during flow start, rotation, auth clearing, and LinkEvent.
// New supplies a shared package lock; set the same custom lock on servers using
// one JaWS instance when coordinating with other authentication methods.
SessionRotationLock sync.Locker
Options []oauth2.AuthCodeOption // authorization URL options, e.g. oauth2.AccessTypeOffline; never sent to token exchange
// RequireVerifiedAdminEmail requires email_verified for a non-empty admin list.
//
// It defaults to true in profile mode and false in OIDC mode. When true,
// providers that omit email_verified cannot grant admin access through a
// non-empty list. Set before serving requests.
// Ordinary login is unaffected.
RequireVerifiedAdminEmail bool
// contains filtered or unexported fields
}
Server provides OIDC or OAuth2 profile authentication for JaWS sessions.
Create one with New or NewDebug. Its methods are safe for concurrent use; the exported configuration fields and callbacks should be set before serving requests.
func New ¶
New creates a Server providing OIDC or OAuth2 profile authentication for JaWS sessions.
It configures the Server from cfg and registers the login, logout and OAuth2 callback endpoints via handleFn. A nil jw returns ErrServerNilJaws. Check both err and Valid before serving protected routes; an invalid Server leaves its wrapped handlers unprotected.
func NewDebug ¶ added in v0.2.0
func NewDebug(jw *jaws.Jaws, cfg *Config, handleFn HandleFunc, overrideUrl string) (srv *Server, err error)
NewDebug behaves like New but can override the scheme and host of cfg.RedirectURL.
overrideUrl supplies the replacement scheme and host (an empty overrideUrl disables the override), which is useful when serving behind a different public address during development.
A nil jw returns ErrServerNilJaws and a nil Server. Otherwise a non-nil Server is always returned. Authentication is configured, and the login, logout and callback handlers registered via handleFn, only when cfg, handleFn and cfg.RedirectURL are all provided; setup errors are returned with the Server.
func (*Server) CurrentClaims ¶ added in v1.5.0
CurrentClaims returns this provider's claims only while authentication and the JaWS session are live. It is useful when several providers share JaWS. Treat the returned session map as read-only, and recheck before protected writes because the session may close after this call.
func (*Server) GetAdmins ¶ added in v0.6.0
GetAdmins returns a sorted list of the administrator emails. If empty, everyone is considered an administrator.
func (*Server) HandleAuthResponse ¶
func (srv *Server) HandleAuthResponse(hw http.ResponseWriter, hr *http.Request)
HandleAuthResponse handles the OIDC or OAuth2 profile callback endpoint.
For GET requests it validates the state, exchanges the authorization code using the stored PKCE verifier, verifies the ID token or authenticated profile, and stores claims in a new session. A link flow instead invokes Server.LinkEvent and keeps the original session. It invokes Server.LoginEvent after a new sign-in or Server.LoginFailed on login or link failure. Non-GET requests receive 405.
Rotation discards pre-login application data and requires a free JaWS session slot. If no slot is available, existing authentication is preserved and the default response is 503. The user must restart login after capacity becomes available.
func (*Server) HandleLink ¶ added in v1.5.0
func (srv *Server) HandleLink(hw http.ResponseWriter, hr *http.Request)
HandleLink begins a provider flow for linking to the caller's existing identity. The application must authorize this POST before calling it and recheck that identity in LinkEvent when the provider returns. On success it responds with a 303 redirect to the provider. It returns 405 with Allow: POST for other methods, 403 for a cross-origin or missing session, and 500 when linking is not configured. Starting a link replaces any pending flow on this server, including a running login callback.
func (*Server) HandleLogin ¶
func (srv *Server) HandleLogin(hw http.ResponseWriter, hr *http.Request)
HandleLogin begins the configured OIDC or OAuth2 profile login flow.
For GET requests it stores the state, PKCE verifier and, for OIDC, nonce in the session, then responds with a 302 redirect to the provider's authorization URL. It replaces any pending flow on this server, canceling a running callback or link. If no usable session is available, it returns 503 with Retry-After instead. Non-GET requests receive 405 with Allow: GET.
func (*Server) HandleLogout ¶
func (srv *Server) HandleLogout(hw http.ResponseWriter, hr *http.Request)
HandleLogout clears this server's authentication in the session and redirects.
For GET requests it clears auth and responds with a 302 redirect to the sanitized referrer (or "/"). LogoutEvent follows EventFunc's ordering rules. Non-GET requests receive 405 with Allow: GET.
func (*Server) Handler ¶
Handler returns a http.Handler that renders the named jaws.Template with dot and requires an authenticated user.
Unauthenticated GET begins login; other unauthenticated methods receive 403. A GET request during a running login callback may return 409. An invalid, non-nil Server returns the unprotected template handler.
func (*Server) HandlerAdmin ¶ added in v0.6.0
HandlerAdmin returns a http.Handler that renders the named jaws.Template with dot and requires an authenticated administrator.
Unauthenticated GET begins login; other unauthenticated methods receive 403. Authenticated non-admins receive 403. Server.RequireVerifiedAdminEmail applies. A GET request during a running login callback may return 409. An invalid, non-nil Server returns the unprotected template handler.
func (*Server) IsAdmin ¶ added in v0.6.0
IsAdmin returns true if email belongs to an admin, if the list of admins is empty, or if srv is nil.
It parses a raw address using the rules in Server.SetAdmins. This lookup cannot verify email ownership. Server.WrapAdmin, Server.HandlerAdmin and JawsAuth.IsAdmin also enforce Server.RequireVerifiedAdminEmail.
func (*Server) Logout ¶ added in v1.2.0
Logout clears this server's authentication state for sess.
It stops the auth timer and clears claims, token source, email and its verification flag, expiry, and in-flight OAuth flow keys, then marks the session dirty. If auth was present, it reloads its pages and may call Server.LogoutEvent under EventFunc's ordering rules. It returns false for a nil receiver or session, and true otherwise. The hr argument may be nil.
It performs no HTTP redirect. An HTTP handler can build its own post-logout response. A JaWS event handler cannot use jaws.Request.Redirect after Logout queues Reload, which closes the connection; use an HTTP logout endpoint instead. It takes SessionRotationLock, if set, and releases it before LogoutEvent runs.
func (*Server) Set403Handler ¶ added in v0.6.0
Set403Handler sets the handler used to serve 403 Forbidden responses to authenticated non-admin users.
A nil h restores the default handler. It is safe for concurrent use.
func (*Server) SetAdmins ¶ added in v0.6.0
SetAdmins sets the emails of administrators.
Valid addresses are parsed with mail.ParseAddress; other nonempty entries are retained. ASCII letters are lowercased. Non-ASCII characters are matched exactly. If empty, everyone is considered an administrator. Session checks also apply Server.RequireVerifiedAdminEmail.
Sessions losing admin access have their JaWS requests retired with a page reload; they remain authenticated and can reopen non-admin pages.
func (*Server) Valid ¶ added in v0.2.0
Valid returns true if OIDC or OAuth2 profile authentication is configured.
func (*Server) Wrap ¶
Wrap returns a http.Handler that requires an authenticated user before invoking h.
Unauthenticated GET begins login; other unauthenticated methods receive 403. A GET request during a running login callback may return 409. An invalid Server returns h.
func (*Server) WrapAdmin ¶ added in v0.6.0
WrapAdmin returns a http.Handler that requires an authenticated administrator before invoking h.
Unauthenticated GET begins login; other unauthenticated methods receive 403. Authenticated non-admins receive 403. Server.RequireVerifiedAdminEmail applies. A GET request during a running login callback may return 409. An invalid Server returns h.