jawsauth

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 25 Imported by: 1

README

build coverage Docs

jawsauth

OIDC and OAuth2 profile authentication for JaWS sessions. Both modes use authorization-code state and PKCE (S256). Wrap and Handler require a login; WrapAdmin and HandlerAdmin also apply the SetAdmins allowlist.

Setup

Config requires RedirectURL, Issuer and ClientID. The issuer, effective provider endpoints and JWKS URI must use HTTPS; AllowInsecureIssuer permits HTTP for tests and development. OIDC mode discovers provider endpoints, verifies the ID token and nonce, and attempts refresh before expiry when the provider issues a refresh token. Request offline access with the offline_access scope for OIDC providers that support it, or oauth2.AccessTypeOffline in Server.Options for Google. Check both the error from New and Server.Valid() before serving protected routes; an invalid server can return handlers without authentication.

Profile mode requires AuthURL, TokenURL and UserInfoURL, plus a ProfileSubject function that extracts a stable subject from the authenticated profile. Profile mode sets the iss claim to Issuer and sub to the ProfileSubject result. The iss+sub pair identifies an account, so use a distinct Issuer for each provider. Email and names are not identity proof. Profile JSON numbers arrive as json.Number to preserve large IDs. Profile authentication expires after 24 hours or the access token's earlier expiry. An explicit expires_in: 0 in the token response is rejected.

Set Jaws.MaxSessions and Jaws.MaxSessionsPerIP to bound sessions created by unauthenticated requests; both limits are unlimited by default. A login start, including an unauthenticated protected GET, can retain its session for about ten minutes even if the client never reaches the provider. By default, login keeps the same session and its application data, so a one-session limit permits login. Set Server.RotateSessionOnLogin before serving requests when an attacker can make a victim use an attacker-known pre-login cookie, reach JaWS from the same client IP JaWS sees for the victim, and cannot learn the later cookie. Rotation discards pre-login application data and needs a free slot under both limits; MaxSessionsPerIP = 1 then prevents login. If a slot is unavailable, the default response is 503 with Retry-After: 60, and the existing session remains available.

Multiple providers

  • Providers sharing JaWS must have distinct Namespace values and callback directories; a shared namespace can clear another provider's login. Add each provider's registered paths to the other servers' HandledPaths so return targets cannot enter another provider's auth endpoints.
  • New replaces Jaws.MakeAuth when it configures authentication. When servers share JaWS, capture jw.MakeAuth immediately after each configured New, then install a composite function so templates use the intended provider's authentication and admin policy. Each server's Wrap, Handler and CurrentClaims check that provider's authentication.
  • Register HandleLink as a POST handler to enable linking; New does not register it. Authorize the session before calling it. In LinkEvent, recheck the original provider's CurrentClaims before writing the link. Linking keeps the session; ordinary login keeps it and leaves other providers signed in. With RotateSessionOnLogin, login signs out other providers, and re-login calls its LogoutEvent on the old session before storing the new sign-in. Calling Logout on that event session cancels it. Other providers' LogoutEvent may run later with a nil request. Before using one to log out another provider, check its CurrentClaims. Starting a link replaces this server's pending flow in the same session, including a running login callback.
  • New shares one process-wide SessionRotationLock by default. To coordinate with other authentication methods or isolate independent JaWS instances, set a custom lock before serving; servers sharing a JaWS must use the same lock. jawsauth holds it during flow start, rotation, in-place login claim storage, authentication clearing and LinkEvent. Do not take the lock around jawsauth handlers or Server.Logout, or within LinkEvent; do not call Server.Logout from LinkEvent. Bound LinkEvent I/O with a timeout; other sessions sharing the lock wait. One provider's logout does not cancel another provider's pending link.

Admin access

Profile mode requires a verified email for a non-empty admin list by default; OIDC mode does not. Set RequireVerifiedAdminEmail = true in OIDC mode unless the provider guarantees verified addresses. In profile mode, ProfileSubject may map a provider verification signal to email_verified; disable the check only with the same guarantee. Providers without a verification signal cannot grant admin access while the check is enabled. Microsoft warns against using its email claim for authorization; use application policy based on a stable identifier for Entra ID. OIDC UserInfo fallback requires its sub to match the ID token's nonempty sub. Its email_verified applies only to an email it supplies or one matching the ID token email exactly. mail and public_email never count as verified.

SetAdmins parses valid addresses and retains other nonempty entries. It trims whitespace and ignores ASCII case. An empty list allows every authenticated user through the admin handlers. Server.IsAdmin(email) checks only list membership; JawsAuth.IsAdmin and the admin handlers enforce email verification when required. Neither IsAdmin method proves a live login; check CurrentClaims before protected actions.

Session lifetime

Pending OAuth flows expire after ten minutes. jawsauth extends the original JaWS session's grace for the pending flow. Unauthenticated protected GETs reuse a pending login's state, return target and grace deadline while more than two minutes remain; near expiry, they start a new flow and extend grace. Once in-place login stores claims, protected GETs with that session cookie return 409 until login notification completes, unless LoginFailed handles them. CurrentClaims remains nil during that interval. Successful in-place login reloads active JaWS pages after LoginEvent. Logout and auth expiry clear this server's credentials and reload every JaWS page in the session. Auth expiry preserves a pending login but cancels a pending link. Explicit logout on the live session cancels either flow. A new login on the same server and session, including one started by Wrap or Handler, cancels a pending link.

Use an HTTP endpoint for a post-logout redirect. When Server.Logout clears authentication, it reloads pages and closes their sockets, so a later JaWS Request.Redirect cannot deliver the redirect.

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

Constants

This section is empty.

Variables

View Source
var ErrConfig errConfig

ErrConfig matches all configuration validation errors.

View Source
var ErrConfigEndpointMustBeHTTPS = errors.New("provider endpoint must use https")

ErrConfigEndpointMustBeHTTPS means a provider endpoint must use HTTPS, or HTTP when AllowInsecureIssuer is enabled.

View Source
var ErrConfigIssuerMustBeHTTPS = errors.New("issuer url must use https")

ErrConfigIssuerMustBeHTTPS means Issuer must use HTTPS, or HTTP when AllowInsecureIssuer is enabled.

View Source
var ErrConfigMissingValue = errors.New("config value is missing")

ErrConfigMissingValue means a required configuration value is missing.

View Source
var ErrConfigURLMissingHost = errors.New("url host is missing")

ErrConfigURLMissingHost means a configured URL does not include a host.

View Source
var ErrConfigURLNotAbsolute = errors.New("url is not absolute")

ErrConfigURLNotAbsolute means a configured URL is not absolute.

View Source
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.

View Source
var ErrOAuth2ExpiredState = errors.New("oauth2 expired state")

ErrOAuth2ExpiredState means the provider returned after the flow lifetime.

View Source
var ErrOAuth2InvalidOrigin = errors.New("oauth2 invalid origin")

ErrOAuth2InvalidOrigin means a link start request failed the same-origin check.

View Source
var ErrOAuth2InvalidProfile = errors.New("oauth2 invalid profile")

ErrOAuth2InvalidProfile means the profile or access token could not prove a stable subject.

View Source
var ErrOAuth2LinkRejected = errors.New("oauth2 link rejected")

ErrOAuth2LinkRejected means the application did not accept a proven link.

View Source
var ErrOAuth2LoginInProgress = errors.New("oauth2 login already in progress")

ErrOAuth2LoginInProgress means a callback has consumed the pending login state.

View Source
var ErrOAuth2MissingPKCEVerifier = errors.New("oauth2 missing pkce verifier")

ErrOAuth2MissingPKCEVerifier means the callback session did not contain the required PKCE verifier.

View Source
var ErrOAuth2MissingSession = errors.New("oauth2 missing session")

ErrOAuth2MissingSession means the session or its pending flow is no longer usable.

View Source
var ErrOAuth2MissingState = errors.New("oauth2 missing state")

ErrOAuth2MissingState means the callback session did not contain the expected state value.

View Source
var ErrOAuth2NotConfigured = errors.New("oauth2 not configured")

ErrOAuth2NotConfigured means OAuth2/OIDC is not configured on the Server.

View Source
var ErrOAuth2WrongState = errors.New("oauth2 wrong state")

ErrOAuth2WrongState means the callback state value did not match the stored session state.

View Source
var ErrOIDCDiscovery = errors.New("oidc discovery failed")

ErrOIDCDiscovery means OIDC provider discovery failed.

View Source
var ErrOIDCInvalidIDToken = errors.New("oidc invalid id_token")

ErrOIDCInvalidIDToken means id_token verification failed.

View Source
var ErrOIDCMissingIDToken = errors.New("oidc missing id_token")

ErrOIDCMissingIDToken means the token response did not include an id_token.

View Source
var ErrOIDCMissingNonce = errors.New("oidc missing nonce")

ErrOIDCMissingNonce means the login request did not include a nonce.

View Source
var ErrOIDCNonceMismatch = errors.New("oidc nonce mismatch")

ErrOIDCNonceMismatch means the id_token nonce did not match the stored session nonce.

View Source
var ErrOIDCProviderMetadata = errors.New("oidc provider metadata invalid")

ErrOIDCProviderMetadata means discovered OIDC metadata was invalid.

View Source
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.

View Source
var ErrUserInfoInvalidResponse = errors.New("userinfo invalid response")

ErrUserInfoInvalidResponse means the UserInfo response was not one JSON object.

View Source
var ErrUserInfoStatus = errors.New("userinfo status")

ErrUserInfoStatus means the UserInfo endpoint returned a non-200 HTTP status.

View Source
var ErrUserInfoTooLarge = errors.New("userinfo response too large")

ErrUserInfoTooLarge means the authenticated profile exceeded the response limit.

View Source
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.

func (*Config) Validate

func (cfg *Config) Validate() error

Validate checks whether cfg contains usable OIDC/OAuth2 settings.

It checks required fields and absolute URLs with hosts. Configured issuer and provider endpoints require HTTPS unless AllowInsecureIssuer permits HTTP. Returned failures match ErrConfig.

type EventFunc added in v0.3.0

type EventFunc func(sess *jaws.Session, hr *http.Request)

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. LoginEvent can read claims from sess with Server.SessionKey. During in-place login, Server.CurrentClaims returns nil until the event ends. LogoutEvent receives a nil request for timer cleanup, deferred delivery, or a call to Server.Logout with a nil request. With Server.RotateSessionOnLogin, re-login calls LogoutEvent on the old session before storing the new sign-in; calling Logout there cancels it. For cross-provider cleanup, check the other Server's CurrentClaims before calling Logout; 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 handles OAuth callback failures and flow conflicts.

It receives login and link start conflicts, and protected GETs while an in-place login notification is pending. 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

type HandleFunc func(uri string, handler http.Handler)

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

func (a *JawsAuth) Data() (x map[string]any)

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

func (a *JawsAuth) Email() (s string)

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

func (a *JawsAuth) EmailVerified() (yes bool)

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

func (a *JawsAuth) IsAdmin() (yes bool)

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 flow conflicts; see FailedFunc
	LinkEvent               LinkFunc            // required by HandleLink; register its POST route separately
	// SessionRotationLock is held during flow start, rotation, in-place login
	// claim storage, 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
	// RotateSessionOnLogin replaces the JaWS Session during login.
	//
	// It defaults to false. When enabled, login publishes a new cookie, closes
	// the old Session, and requires a free slot under JaWS session limits.
	// Set it before serving requests.
	RotateSessionOnLogin bool

	// 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

func New(jw *jaws.Jaws, cfg *Config, handleFn HandleFunc) (srv *Server, err error)

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

func (srv *Server) CurrentClaims(sess *jaws.Session) map[string]any

CurrentClaims returns this provider's live authentication claims.

While an in-place login notification is pending, it returns nil. It is useful when several providers share JaWS. Treat the returned map as read-only. The session may close, and an in-place login may change its identity or permissions after this call. Recheck the session and claims before protected writes.

func (*Server) GetAdmins added in v0.6.0

func (srv *Server) GetAdmins() (emails []string)

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 by default stores claims in the existing session. A link flow invokes Server.LinkEvent. It invokes Server.LoginEvent after a new sign-in or Server.LoginFailed on login or link failure. Non-GET requests receive 405.

With Server.RotateSessionOnLogin, login creates a new session and discards pre-login application data. If no session slot is available, existing authentication is preserved and the default response is 503. The user must restart login after capacity becomes available.

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. The default response is 409 while an in-place login notification is pending. Otherwise, starting a link replaces any pending flow for this server and session, 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 for this server and session, canceling a running callback or link, unless an in-place login notification is pending; then the default response is 409. 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

func (srv *Server) Handler(name string, dot any) http.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

func (srv *Server) HandlerAdmin(name string, dot any) http.Handler

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

func (srv *Server) IsAdmin(email string) (yes bool)

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

func (srv *Server) Logout(sess *jaws.Session, hr *http.Request) (cleared bool)

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

func (srv *Server) Set403Handler(h http.Handler)

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

func (srv *Server) SetAdmins(emails []string)

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

func (srv *Server) Valid() bool

Valid returns true if OIDC or OAuth2 profile authentication is configured.

func (*Server) Wrap

func (srv *Server) Wrap(h http.Handler) (rh http.Handler)

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

func (srv *Server) WrapAdmin(h http.Handler) (rh http.Handler)

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.

Jump to

Keyboard shortcuts

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