Documentation
¶
Index ¶
- Constants
- Variables
- func ClientIP(r *http.Request) (netip.Addr, error)
- func MatchWildcard(pattern string, value string) bool
- func RequestUrl(r *http.Request) *url.URL
- func ShouldStartLogin(r *http.Request) bool
- type Action
- type App
- type AuthMethod
- type Authenticator
- func (au *Authenticator) Authenticate(r *http.Request) (AuthMethod, *Session, error)
- func (au *Authenticator) GetAbsRedirectUri(r *http.Request) string
- func (au *Authenticator) HandleCallback(w http.ResponseWriter, r *http.Request) error
- func (au *Authenticator) ProtectedResourceMetadata(r *http.Request) (*OAuthProtectedResource, bool)
- func (au *Authenticator) ServeHTTPOAuthProtectedResource(rw http.ResponseWriter, r *http.Request) error
- func (au *Authenticator) SessionFromAuthorizationHeader(r *http.Request) (AuthMethod, *Session, error)
- func (au *Authenticator) SessionFromClaims(claims ClaimsDecoder) (*Session, error)
- func (au *Authenticator) SessionFromCookie(r *http.Request) (AuthMethod, *Session, error)
- func (au *Authenticator) StartLogin(w http.ResponseWriter, r *http.Request) error
- type CSRFToken
- type ClaimMatch
- type ClaimsDecoder
- type Cookies
- type DeferredResult
- type EvaluationResult
- type MatchAnonymous
- type MatchAuthMethod
- type MatchClaim
- type MatchUser
- type OAuth2Client
- type OAuthProtectedResource
- type OIDCMiddleware
- func (mw *OIDCMiddleware) CaddyModule() caddy.ModuleInfo
- func (mw *OIDCMiddleware) Provision(ctx caddy.Context) error
- func (mw *OIDCMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error
- func (mw *OIDCMiddleware) UnmarshalCaddyfile(dis *caddyfile.Dispenser) error
- func (mw *OIDCMiddleware) Validate() error
- type OIDCProviderModule
- func (*OIDCProviderModule) CaddyModule() caddy.ModuleInfo
- func (m *OIDCProviderModule) Create(ctx caddy.Context) (*Authenticator, error)
- func (m *OIDCProviderModule) Provision(_ caddy.Context) error
- func (m *OIDCProviderModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
- func (m *OIDCProviderModule) Validate() error
- type ProtectedResourceMetadataConfiguration
- type Rule
- type RuleEvaluation
- type Ruleset
- type SameSite
- type Session
- type UserInfoClient
Constants ¶
const ( SessionCtxKey caddy.CtxKey = "oidc_session" AuthMethodCtxKey caddy.CtxKey = "oidc_auth_method" )
const ( DefaultRedirectUriPath = "/oauth2/callback" DefaultUsernameClaim = "sub" )
const Leeway = time.Second * 5
const ModuleID = "oidc"
const WellKnownOAuthProtectedResourcePath = "/.well-known/oauth-protected-resource"
Variables ¶
var ( AnonymousSession = &Session{ Anonymous: true, Claims: json.RawMessage(`{}`), } )
var AuthFromRequestSources = []func(*Authenticator, *http.Request) (AuthMethod, *Session, error){ (*Authenticator).SessionFromAuthorizationHeader, (*Authenticator).SessionFromCookie, }
AuthFromRequestSources are request token sources that are expected to return a valid non-anonymous non-expired session if the error is not-nil. Returning ErrNoAuthorization or *oidc.TokenExpiredError indicates that no valid token was found. Any other error is returned directly.
var DefaultCookieOptions = Cookies{ Name: "caddy", SameSite: SameSite{http.SameSiteLaxMode}, Insecure: false, Domain: "", Path: "/", }
var ErrAccessDenied = errors.New("access denied")
var ErrInvalidAction = errors.New("not a valid Action")
var ErrInvalidAuthMethod = errors.New("not a valid AuthMethod")
var ErrInvalidEvaluationResult = errors.New("not a valid EvaluationResult")
var ErrNoAuthorization = errors.New("no authorization provided")
Functions ¶
func ClientIP ¶
ClientIP gets the real client IP address from the request using the same method Caddy would
func MatchWildcard ¶
MatchWildcard matches a possible wildcard pattern against a value. Uses the same wildcard matching logic as caddyhttp.MatchHeader.
func RequestUrl ¶
RequestUrl returns the original fully qualified request URL made by the client before any intermediate proxies. Assumes that Caddy has already sanitized any X-Forwarded-* headers.
func ShouldStartLogin ¶
ShouldStartLogin returns true if the request should start the authorization flow on a failed authentication attempt based on if the request is likely coming from a browser.
Types ¶
type Action ¶
type Action uint8
Action represents the possible actions to take when a rule is matched. ENUM(allow, deny)
func ParseAction ¶ added in v0.2.1
ParseAction attempts to convert a string to a Action.
func (*Action) AppendText ¶ added in v0.2.1
AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.
Implementations must not retain b, nor mutate any bytes within b[:len(b)].
func (Action) IsValid ¶ added in v0.2.1
IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values
func (Action) MarshalText ¶
MarshalText implements the text marshaller method.
func (*Action) UnmarshalText ¶
UnmarshalText implements the text unmarshaller method.
type App ¶
type App struct {
Providers map[string]*OIDCProviderModule `json:"providers,omitempty"`
// contains filtered or unexported fields
}
func (*App) CaddyModule ¶
func (*App) CaddyModule() caddy.ModuleInfo
type AuthMethod ¶ added in v0.2.3
type AuthMethod string
AuthMethod represents one of the supported authentication methods. ENUM(none, bearer, cookie)
const ( // AuthMethodNone is a AuthMethod of type none. AuthMethodNone AuthMethod = "none" // AuthMethodBearer is a AuthMethod of type bearer. AuthMethodBearer AuthMethod = "bearer" // AuthMethodCookie is a AuthMethod of type cookie. AuthMethodCookie AuthMethod = "cookie" )
func ParseAuthMethod ¶ added in v0.2.3
func ParseAuthMethod(name string) (AuthMethod, error)
ParseAuthMethod attempts to convert a string to a AuthMethod.
func (*AuthMethod) AppendText ¶ added in v0.2.3
func (x *AuthMethod) AppendText(b []byte) ([]byte, error)
AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.
Implementations must not retain b, nor mutate any bytes within b[:len(b)].
func (AuthMethod) IsValid ¶ added in v0.2.3
func (x AuthMethod) IsValid() bool
IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values
func (AuthMethod) MarshalText ¶ added in v0.2.3
func (x AuthMethod) MarshalText() ([]byte, error)
MarshalText implements the text marshaller method.
func (AuthMethod) String ¶ added in v0.2.3
func (x AuthMethod) String() string
String implements the Stringer interface.
func (*AuthMethod) UnmarshalText ¶ added in v0.2.3
func (x *AuthMethod) UnmarshalText(text []byte) error
UnmarshalText implements the text unmarshaller method.
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator holds the built configuration for an OIDC provider and authentication logic
func (*Authenticator) Authenticate ¶
func (au *Authenticator) Authenticate(r *http.Request) (AuthMethod, *Session, error)
Authenticate the incoming request by either reading a token from the Authorization header or the session token, preferring an explicit token from the Authorization header.
func (*Authenticator) GetAbsRedirectUri ¶
func (au *Authenticator) GetAbsRedirectUri(r *http.Request) string
GetAbsRedirectUri returns the absolute redirect URI, resolving it relative to the request URL if necessary.
func (*Authenticator) HandleCallback ¶
func (au *Authenticator) HandleCallback(w http.ResponseWriter, r *http.Request) error
HandleCallback handles the callback from the authorization endpoint.
func (*Authenticator) ProtectedResourceMetadata ¶
func (au *Authenticator) ProtectedResourceMetadata(r *http.Request) (*OAuthProtectedResource, bool)
ProtectedResourceMetadata returns the OAuth protected resource metadata for this authenticator. If protected resource metadata is not enabled, then false is returned.
func (*Authenticator) ServeHTTPOAuthProtectedResource ¶
func (au *Authenticator) ServeHTTPOAuthProtectedResource(rw http.ResponseWriter, r *http.Request) error
ServeHTTPOAuthProtectedResource returns the OAuth protected resource metadata for the endpoint .well-known/oauth-protected-resource. If the endpoint is disabled, then a 404 not found response is returned.
func (*Authenticator) SessionFromAuthorizationHeader ¶
func (au *Authenticator) SessionFromAuthorizationHeader(r *http.Request) (AuthMethod, *Session, error)
SessionFromAuthorizationHeader extracts the session an access or ID token parsed from the request Authorization header. Returns ErrNoAuthorization if a valid token could not be found or a valid, signed token exists but is expired.
func (*Authenticator) SessionFromClaims ¶
func (au *Authenticator) SessionFromClaims(claims ClaimsDecoder) (*Session, error)
SessionFromClaims extracts a session from claims contained within the given ClaimsDecoder.
func (*Authenticator) SessionFromCookie ¶
func (au *Authenticator) SessionFromCookie(r *http.Request) (AuthMethod, *Session, error)
SessionFromCookie extracts the session from the secure request cookie. Returns ErrNoAuthorization if the cookie is not found or a signed token does exist but is not expired.
func (*Authenticator) StartLogin ¶
func (au *Authenticator) StartLogin(w http.ResponseWriter, r *http.Request) error
StartLogin starts the authorization flow by setting the state cookie and redirecting to the authorization endpoint. The state cookie is in the format of `<cookie_name>|<state>`, with the value containing the PKCE code verifier. The OAuth2 redirect URI is set to the configured redirect URI made absolute relative to the request URL.
type ClaimMatch ¶
type ClaimsDecoder ¶
A ClaimsDecoder is a type that can decode arbitrary claims into a value using JSON. The value might be a json.RawMessage.
type Cookies ¶
type Cookies struct {
Name string `json:"name"`
SameSite SameSite `json:"same_site"`
Insecure bool `json:"insecure,omitempty"`
Domain string `json:"domain,omitempty"`
Path string `json:"path"`
}
func (*Cookies) UnmarshalCaddyfile ¶
UnmarshalCaddyfile sets up the Cookies from Caddyfile tokens.
syntax
cookie <name> | {
name <name>
same_site <same_site>
insecure
domain <domain>
path <path>
}
type DeferredResult ¶
type DeferredResult[T any] struct { // contains filtered or unexported fields }
DeferredResult represents a computation that runs in the background.
func Defer ¶
func Defer[T any](fn func() (T, error)) *DeferredResult[T]
Defer starts the provided function in a separate goroutine and returns a handle to the result.
type EvaluationResult ¶ added in v0.2.1
type EvaluationResult uint8
EvaluationResult represents the possible results of ruleset evaluation. ENUM(implicit deny, explicit deny, allow)
const ( // EvaluationResultImplicitDeny is a EvaluationResult of type Implicit Deny. EvaluationResultImplicitDeny EvaluationResult = iota // EvaluationResultExplicitDeny is a EvaluationResult of type Explicit Deny. EvaluationResultExplicitDeny // EvaluationResultAllow is a EvaluationResult of type Allow. EvaluationResultAllow )
func ParseEvaluationResult ¶ added in v0.2.1
func ParseEvaluationResult(name string) (EvaluationResult, error)
ParseEvaluationResult attempts to convert a string to a EvaluationResult.
func (*EvaluationResult) AppendText ¶ added in v0.2.1
func (x *EvaluationResult) AppendText(b []byte) ([]byte, error)
AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.
Implementations must not retain b, nor mutate any bytes within b[:len(b)].
func (EvaluationResult) IsValid ¶ added in v0.2.1
func (x EvaluationResult) IsValid() bool
IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values
func (EvaluationResult) MarshalText ¶ added in v0.2.1
func (x EvaluationResult) MarshalText() ([]byte, error)
MarshalText implements the text marshaller method.
func (EvaluationResult) String ¶ added in v0.2.1
func (x EvaluationResult) String() string
String implements the Stringer interface.
func (*EvaluationResult) UnmarshalText ¶ added in v0.2.1
func (x *EvaluationResult) UnmarshalText(text []byte) error
UnmarshalText implements the text unmarshaller method.
type MatchAnonymous ¶
type MatchAnonymous struct{}
MatchAnonymous matches requests that are anonymous or do not have a valid session in the request context.
func (*MatchAnonymous) CaddyModule ¶
func (*MatchAnonymous) CaddyModule() caddy.ModuleInfo
func (*MatchAnonymous) MatchWithError ¶
func (*MatchAnonymous) MatchWithError(r *http.Request) (bool, error)
func (*MatchAnonymous) UnmarshalCaddyfile ¶
func (*MatchAnonymous) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
type MatchAuthMethod ¶ added in v0.2.3
type MatchAuthMethod struct {
Match []AuthMethod `json:"match,omitempty"`
}
MatchAuthMethod matches the authentication method used for the incoming request.
func (*MatchAuthMethod) CaddyModule ¶ added in v0.2.3
func (*MatchAuthMethod) CaddyModule() caddy.ModuleInfo
func (*MatchAuthMethod) MatchWithError ¶ added in v0.2.3
func (m *MatchAuthMethod) MatchWithError(r *http.Request) (bool, error)
func (*MatchAuthMethod) UnmarshalCaddyfile ¶ added in v0.2.3
func (m *MatchAuthMethod) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
type MatchClaim ¶
type MatchClaim []ClaimMatch
MatchClaim matches claims in a request session. The claim value in the session must be a string or an array of strings. If the claim value is an array, the match succeeds if any of the values match.
func (*MatchClaim) CaddyModule ¶
func (*MatchClaim) CaddyModule() caddy.ModuleInfo
func (*MatchClaim) MatchWithError ¶
func (m *MatchClaim) MatchWithError(r *http.Request) (bool, error)
func (*MatchClaim) UnmarshalCaddyfile ¶
func (m *MatchClaim) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
type MatchUser ¶
type MatchUser struct {
Usernames []string `json:"usernames,omitempty"`
}
MatchUser matches the request against a list of wildcard-matched usernames present within the session stored in the incoming context. If the session is anonymous, no usernames are considered and the match always fails.
func (*MatchUser) CaddyModule ¶
func (*MatchUser) CaddyModule() caddy.ModuleInfo
func (*MatchUser) MatchWithError ¶
type OAuth2Client ¶
type OAuth2Client interface {
AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string
Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)
Scopes() []string
ClientID() string
}
OAuth2Client is an interface for the oauth2 client.
type OAuthProtectedResource ¶
type OAuthProtectedResource struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
ScopesSupported []string `json:"scopes_supported"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
// Audience is a custom extension to the OAuth Protected Resource Metadata spec.
Audience string `json:"audience,omitempty"`
}
OAuthProtectedResource is the JSON payload sent from /.well-known/oauth-protected-resource or advertised in WWW-Authenticate on 401 responses.
func (*OAuthProtectedResource) WWWAuthenticate ¶
func (md *OAuthProtectedResource) WWWAuthenticate() string
WWWAuthenticate returns the value of the WWW-Authenticate header for this resource. https://datatracker.ietf.org/doc/html/rfc9728#name-use-of-www-authenticate-for https://datatracker.ietf.org/doc/html/rfc6750#section-3
type OIDCMiddleware ¶
type OIDCMiddleware struct {
Provider string `json:"provider"`
Policies Ruleset `json:"policies"`
// contains filtered or unexported fields
}
func (*OIDCMiddleware) CaddyModule ¶
func (mw *OIDCMiddleware) CaddyModule() caddy.ModuleInfo
func (*OIDCMiddleware) ServeHTTP ¶
func (mw *OIDCMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error
ServeHTTP implements caddyhttp.MiddlewareHandler. It wraps interceptRequest to handle errors to ensure any error returned is a caddyhttp.HandlerError. Without this, Caddy's error_directive does not properly set error replacer vars, which can result in HTTP 200 responses when it tries to parse `{err.status_code}`.
func (*OIDCMiddleware) UnmarshalCaddyfile ¶
func (mw *OIDCMiddleware) UnmarshalCaddyfile(dis *caddyfile.Dispenser) error
UnmarshalCaddyfile sets up the OIDCMiddleware from Caddyfile tokens.
oidc example {
allow|deny {
...
}
}
func (*OIDCMiddleware) Validate ¶
func (mw *OIDCMiddleware) Validate() error
type OIDCProviderModule ¶
type OIDCProviderModule struct {
Issuer string `json:"issuer"`
ClientID string `json:"client_id"`
SecretKey string `json:"secret_key"`
RedirectURI string `json:"redirect_uri,omitempty"`
TLSInsecureSkipVerify bool `json:"tls_insecure_skip_verify,omitempty"`
Cookie *Cookies `json:"cookie,omitempty"`
ProtectedResourceMetadata *ProtectedResourceMetadataConfiguration `json:"protected_resource_metadata,omitempty"`
Scope []string `json:"scope,omitempty"`
Username string `json:"username,omitempty"`
Claims []string `json:"claims,omitempty"`
}
OIDCProviderModule holds the configuration for an OIDC provider
func (*OIDCProviderModule) CaddyModule ¶
func (*OIDCProviderModule) CaddyModule() caddy.ModuleInfo
func (*OIDCProviderModule) Create ¶
func (m *OIDCProviderModule) Create(ctx caddy.Context) (*Authenticator, error)
Create creates an Authenticator instance from this provider configuration.
func (*OIDCProviderModule) Provision ¶
func (m *OIDCProviderModule) Provision(_ caddy.Context) error
func (*OIDCProviderModule) UnmarshalCaddyfile ¶
func (m *OIDCProviderModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile sets up the OIDCProviderModule instance from Caddyfile tokens.
{
issuer <issuer>
client_id <client_id>
redirect_uri [<redirect_uri>]
secret_key <secret_key>
tls_insecure_skip_verify
discovery_url <discovery_url>
scope [<scope>...]
username <username>
claim [<claim>...]
protected_resource <protected_resource>
cookie <cookie>
}
func (*OIDCProviderModule) Validate ¶
func (m *OIDCProviderModule) Validate() error
type ProtectedResourceMetadataConfiguration ¶
type ProtectedResourceMetadataConfiguration struct {
Disable bool `json:"disable"`
Audience bool `json:"audience,omitempty"`
}
func (*ProtectedResourceMetadataConfiguration) UnmarshalCaddyfile ¶
func (c *ProtectedResourceMetadataConfiguration) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile sets up the ProtectedResourceMetadataConfiguration from Caddyfile tokens.
syntax
protected_resource_metadata disable | {
audience
}
type Rule ¶ added in v0.2.1
type Rule struct {
ID string `json:"id,omitempty"`
Action Action `json:"action"`
MatcherSetsRaw caddy.ModuleMap `json:"match,omitempty" caddy:"namespace=http.matchers"`
Matchers caddyhttp.MatcherSet `json:"-"`
}
func (*Rule) MatchWithError ¶ added in v0.2.1
MatchWithError returns true if the request matches the rule. Unlike caddyhttp.MatcherSets, an empty matcher set never matches a request.
type RuleEvaluation ¶ added in v0.2.1
type RuleEvaluation struct {
Result EvaluationResult `json:"result"`
RuleID string `json:"rule_id"`
}
type Ruleset ¶ added in v0.2.1
type Ruleset []*Rule
func (*Ruleset) ContainsAllow ¶ added in v0.2.1
ContainsAllow returns true if the set contains at least one ActionAllow rule.
func (*Ruleset) Evaluate ¶ added in v0.2.1
func (rules *Ruleset) Evaluate(r *http.Request) (e RuleEvaluation, err error)
Evaluate all rules in the set and return the evaluation result. At least one allow rule must match to return EvaluationResultAllow. If any "deny" rule is matched, return EvaluationResultExplicitDeny.
func (*Ruleset) UnmarshalCaddyfile ¶ added in v0.2.1
type SameSite ¶
func (*SameSite) MarshalText ¶
func (*SameSite) UnmarshalCaddyfile ¶
func (*SameSite) UnmarshalText ¶
type Session ¶
type Session struct {
Anonymous bool `json:"-"`
Uid string `json:"u"`
ExpiresAt int64 `json:"e,omitempty"`
Claims json.RawMessage `json:"c,omitempty"`
}
func (*Session) Expires ¶
Expires returns the expiration time of the session. Returns a zero time if the session has no expiration time
func (*Session) HttpCookie ¶
func (s *Session) HttpCookie(cookies *Cookies, encoder *securecookie.SecureCookie) (*http.Cookie, error)
HttpCookie returns the http cookie representation of the cookies