caddy_oidc package - github.com/relvacode/caddy-oidc - Go Packages

caddy_oidc

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 28 Imported by: 0

README

Caddy OIDC

A Caddy plugin for OIDC authentication and authorization.

Inspired by oauth2-proxy but instead of requiring each application to be configured individually, perform authentication and authorization at the Caddy level.

Advantages over oauth2-proxy

  • Avoids the need to configure each application individually, with N+1 oauth2 proxies per application
  • Centralized access logging that includes user ID
  • Easier integration with security tools like fail2ban, etc
  • Anonymous access and client ip-based authorization rules
  • Support for RFC9728 (OAuth 2.0 Protected Resource Metadata)

Installation

Installation can be done either via the provided Docker image (Caddy with only caddy-oidc installed)

ghcr.io/relvacode/caddy-oidc:latest

Or by building caddy with this plugin via xcaddy

FROM caddy:builder AS builder
RUN xcaddy build \
    --with github.com/relvacode/caddy-oidc

Configuration

caddy-oidc has a global and per-route oidc directive.

The global directive is used to describe common OIDC provider configurations that can be used by multiple routes.

{
    oidc {
        issuer https://accounts.google.com
        client_id "<client_id>"
    }
}

A global directive can be given a name, which can be used to reference it in the handler directive. A named global directive inherits the global default (unnamed) provider configuration.

{
    # Inherits the global "default" provider configuration.
    # Any properties set here will override the global default provider.
    oidc example {
        # Inherits:
        # issuer https://accounts.google.com
        # client_id "<client_id>"

        # Replaces `scope`
        scope openid email profile
    }
}

Each route that needs to be authenticated then uses the handler directive. The handler directive inherits provider configuration from the matching global oidc directive, but can be overridden and/or entirely defined inline, see Inheritance.

example.com {
    # Inherit the global "example" provider configuration.
    # A provider name can be omitted to use the global default.
    oidc example {
        # Inherits:
        # issuer https://accounts.google.com
        # client_id "<client_id>"
        # scope openid email profile

        # Replaces any inherited `authenticate` configuration.
        authenticate bearer

        # ...
        # Handler-specific directives

        allow {
            user *
        }
    }
    reverse_proxy localhost:8080
}

Inheritance

This module supports inheritance of configuration from global and named provider directives down to the handler directive.

When a handler directive is provisioned, it will apply a baseline configuration from its inherited parent. Only fields that are not explicitly configured are inherited from the parent configuration.

Inheritance happens after configuration is parsed, so any explicit configuration will override inherited configuration.

{
    oidc {
        issuer https://accounts.google.com
        client_id {env.OAUTH_CLIENT_ID}
    }

    oidc example {
        # Inherits:
        # issuer https://accounts.google.com
        # client_id {env.OAUTH_CLIENT_ID}

        scope openid email profile
    }
}

example.com {
    oidc example {
        # Inherits:
        # issuer https://accounts.google.com
        # client_id {env.OAUTH_CLIENT_ID}
        # scope openid email profile

        # Replaces `scope`
        scope profile
    }
}

Global Directive

Option Description Default
issuer The OIDC issuer URL
client_id The OIDC client ID
client_secret (optional) The OIDC client secret for confidential clients.
tls_insecure_skip_verify (optional) Skip TLS certificate verification with the OIDC provider.
scope (optional) The scope to request from the OIDC provider. The openid scope is required for browser-based login to work. openid
username (optional) The claim to use as the username. Defaults to sub. sub
protected_resource_metadata (optional) Configure or disable RFC9728 support.
authenticate (optional) Configure authentication methods
token_params (optional) Additional key-value parameters for the OAuth code exchange. Values support Caddy placeholders. See Token Parameters.
Default Provider

A global directive without a name is used to configure the default provider.

The default provider is used as a baseline for any named provider configurations and any handler directives that do not explicitly configure a provider.

{
    # An `oidc` directive without a name is used to configure the default provider.
    oidc {
        issuer https://accounts.google.com
        client_id {env.OAUTH_CLIENT_ID}
    }
}
Authentication

This module uses a plugin architecture to allow different authentication methods to be configured under the Caddy plugin namespace http.oidc.authenticator.

When a request requires authentication, authentication methods are tried in the order they are configured. The first authenticator to return a valid session from the request is used. An expired session is ignored, and the next authenticator is tried.

Defaults

To use the default set of authenticators, omit any authenticator or use the default option.

authenticate default

The default configuration is equivalent to the following

authenticate bearer
authenticate cookie {
    name caddy
    secret "{env.COOKIE_SECRET}"
}

[!NOTE] Configuring any authenticate handlers will override the default configuration. Use the default option to include the default configuration.

Require Authentication

By default, authentication is optional. This allows access rules to determine the action to take when a request is not authenticated.

This also allows automatic redirection to the OIDC provider for authentication when the request is made by a browser.

You can disable this behavior by adding the required option. When enabled, any request that is not authenticated will result in a 401 Unauthorized response before evaluating access policy rules.

[!NOTE] It's recommended to leave this option disabled and use access rules to determine the action to take when a request is not authenticated.

authenticate required
Forwarding Authentication

By default, any authentication information from any configured authenticator is stripped from the request before passing it upstream. This behavior can be disabled by adding the preserve_request option.

authenticate preserve_request
Token Parameters

The token_params block allows you to add arbitrary key-value parameters to the OAuth code exchange request. Values support Caddy placeholders, which are resolved at exchange time.

This is useful for authentication flows that require extra parameters beyond the standard OAuth2 fields, such as JWT bearer client assertions (RFC 7523).

token_params {
    client_assertion_type urn:ietf:params:oauth:client-assertion-type:jwt-bearer
    client_assertion {file./var/run/secrets/token}
}

The {file.*} placeholder reads its value from disk on every evaluation, making it suitable for tokens that rotate ( e.g., projected Kubernetes service account tokens).

Workload Identity Federation

Workload Identity Federation (WIF) allows caddy-oidc to authenticate with an OIDC provider **without a client_secret **. Instead, a projected Kubernetes service account token is exchanged for a provider access token using a JWT bearer assertion (RFC 7523).

This is commonly used with Microsoft Entra ID (Azure AD) on OpenShift or AKS clusters where a federated credential is configured on the App Registration.

Using token_params with the {file.*} placeholder, the projected token is re-read from the filesystem on every token exchange, so token rotation is handled automatically.

{
    oidc entra {
        issuer https://login.microsoftonline.com/{tenant}/v2.0
        client_id "<client_id>"
        token_params {
            client_assertion_type urn:ietf:params:oauth:client-assertion-type:jwt-bearer
            client_assertion {file./var/run/secrets/openshift/serviceaccount/token}
        }
        scope openid email profile
        authenticate cookie {
            name caddy
            secret "{env.COOKIE_SECRET}"
        }
    }
}

[!NOTE] While the underlying mechanism (RFC 7523 JWT bearer client assertions) is a standard, this pattern has been tested with Microsoft Entra ID federated credentials. The same token_params approach can be adapted for other providers that accept custom parameters during the token exchange.

Bearer

The bearer authenticator is used to authenticate requests using a JWT bearer token. The bearer JWT must be signed by the OIDC provider.

authenticate bearer

The cookie authenticator is used to authenticate requests using a self-signed session cookie.

Option Description Default
name The name of the cookie.
secret The 32 or 64 byte secret key to encrypt session cookies
domain (optional) The domain of the cookie.
path (optional) The path of the cookie. /
insecure (optional) Disable secure cookies.
same_site (optional) The samesite mode of the cookie. One of lax, strict or none
id_claim (optional) Claims to copy from the ID token.
claim (optional) Claims to copy from the User Info endpoint. Takes precedence over id_claim
redirect_url (optional) The URL to redirect to after authentication. If the URL is relative, the fully qualified URL is constructed using the request host and protocol. /oauth2/callback
max_age (optional) Cookie and session lifetime (e.g. 168h). When set, the browser cookie uses Max-Age and session expiry is now+max_age instead of the OAuth token expiry. Omit or 0 for a browser session cookie with expiry from the token response.

To minimize the size of the cookie, no claims are copied into the session cookie by default. Claims can be copied by specifying the claim or id_claim option if needed for access policy rules or placeholder variables (e.g., for logging).

Enabling session cookie authentication also enables interactive authentication through the browser via the OAuth 2.0 Authorization Code Flow.

Automatic redirection to the OIDC provider for login happens when all the following conditions are met:

  • A session cookie authenticator is configured
  • The request is not authenticated
  • Authentication is not required
  • There is no matching explicit allow or deny rule
  • The request is made by a browser, determined by:
    • Sec-Fetch-Dest is document or iframe
    • Accept header contains text/html
Header

The header authenticator authenticates a JWT token passed via an incoming HTTP request header (without any prefix).

authenticate header X-Api-Key
Query

The query authenticator authenticates a JWT token passed via an incoming HTTP request query parameter.

[!CAUTION] There are several security implications to using query parameters for authentication. See RFC6750 for more information.

authenticate query access_token
RFC9728 Support (protected_resource_metadata)

Caddy OIDC supports RFC9728 (OAuth 2.0 Protected Resource Metadata) to discover the OIDC provider metadata via the well-known URL /.well-known/oauth-protected-resource.

If the request is unauthenticated, passes at least one allow rule, and the request is not made by a browser, then a 401 Unauthorized response is returned with a WWW-Authenticate header conforming to WWW-Authenticate Response.

Settings can be controlled via the oidc directive protected_resource_metadata. The default behavior is to enable.

# Disable RFC9728 support.
# This makes /.well-known/oauth-protected-resource return a 404 Not Found.
protected_resource_metadata off
Audience

As a custom extension to the standard, resource metadata can be configured to include the expected token audience (aud) claim.

If enabled, the metadata response will contain an additional audience field containing the configured client ID of the OIDC provider configuration.

This is designed as an alternative to dynamic client registration to let another client (e.g. a CLI) use JWT Exchange with its own token with the OIDC provider and make requests to this server without prior knowledge of this server's OAuth configuration.

# Include the expected audience field in the metadata
protected_resource_metadata {
    audience
}

Handler Directive

The handler directive is placed on routes to provide authentication and authorization for that route. These directives inherit configuration from the global oidc directive. If a specific provider is named, then it uses that, otherwise it inherits the global defaults. See Inheritance for more information.

A route is only authenticated by caddy-oidc if it is configured with at least once oidc handler directive.

The handler directive must contain at least one allow rule.

If the request is unauthenticated, and there is not an explicit allow or deny rule that matches the request, and the request is made by a browser, then the browser will be automatically redirected to the OIDC provider for authentication.

Access Rules

Each access rule can be either allow or deny. Inspired by AWS IAM policies, each request must match at least one allow rule to be authorized.

Access rules match using Caddy's regular request matchers. Additional HTTP matchers are provided for authentication-specific request matching.

[!CAUTION] Without an explicit user match in an allow policy rule, all requests will be allowed, even anonymous request unless authenticate required is enabled.

If a request matches any deny rule then the request is denied, even if another allow rule matches.

# Allow any authenticated user from example.com except from steve

oidc example {
    allow {
        user *@example.com
    }
    deny {
        user steve@example.com
    }
}

Access rules can be optionally named for logging, if matched then the rule ID will be available as the placeholder variable {http.auth.rule}.

oidc example {
    deny "DenyAnonymousAccess" {
        anonymous
    }
    allow "AllowAnyUserReadAccess" {
        method GET HEAD
        user *
        claim role read
    }
    allow "AllowAdminWriteAccess" {
        method POST PUT PATCH DELETE
        user *
        claim role write
    }
}
HTTP Matchers

In addition to the standard Caddy request matchers, the following matchers are provided. These matchers are only compatible with HTTP requests handled by the handler directive.

User

Matches the username of the authenticated user. A user match will never match an anonymous user.

# Allow any authenticated user

allow {
    user *
}
# Allow any authenticated user from example.com

allow {
    user *@example.com
}
# Allow multiple users

allow {
    user steve
    user bob
    user john
}
Anonymous

Matches request sessions that are anonymous. Anonymous sessions are sessions that have not been authenticated by the OIDC provider.

# Allow anonymous requests to /healthcheck

allow {
    anonymous
    path /healthcheck
}
Claim

Matches claims in the request session.

If the session claim is an array, then the request must match at least one value in the array. Any non-string claim values are ignored and will not match.

Multiple values for a single claim directive are treated as a logical OR. If no values are specified, the matcher only checks for the claim's existence.

[!NOTE] Any claims used here must be configured in the cookie authenticator if used.

# Allow requests containing role = write

allow {
    claim role write
}
# Allow requests containing role = read OR role = write

allow {
    claim role read write
}
# Allow requests containing role = read AND role = write

allow {
    claim role read
    claim role write
}
# Allow requests containing sub = steve@example.com AND role = read

allow {
    claim sub steve@example.com
    claim role read
}
# Deny all requests missing the 'role' claim

deny {
    not {
        claim role
    }
}

Replacer variables are supported in both claim name and claim value.

# Allow requests containing host = {http.host}

allow {
    claim host {http.host}
}

Wildcard matching is also supported in claim values.

# Allow requests where the role claim starts with "read:"

allow {
    claim role read:*
}
Auth Method

Matches the authentication method used to authenticate the request.

Possible values are

  • cookie - The request was authenticated using a session cookie
  • bearer - The request was authenticated using a bearer JWT token
  • header - The request was authenticated using a JWT token passed in an HTTP header
  • query - The request was authenticated using a JWT token passed in a query parameter
  • none - The request was not authenticated
# Deny all requests using JWT bearer authentication

deny {
    auth_method bearer
}
Placeholder Variables

When a request passes through the oidc handler, the following placeholder variables are available:

Placeholder Description
http.auth.user.id The username extracted from the username option of the global directive
http.auth.user.anonymous true if the session is not authenticated otherwise false
http.auth.method The authentication method of the request. One of the available auth methods
http.auth.user.claim.* Set for each claim provided by the matched authenticator
http.auth.rule The named access policy rule that matched the request
http.auth.result The acccess rule evaluation result. One of allow, implicit deny or explicit deny

Because the oidc handler is ordered after the header handler, to set these variables in response headers, you must use the defer option

header X-User-Claim-Email {http.auth.user.claim.email} {
    defer
}
Claim Value Formatting
  • Simple values like strings, booleans, and numbers are formatted as plain values
  • Null values are empty
  • Objects are formatted as JSON
  • Arrays are formatted using the above rules for each element, joined by commas. Nested arrays are formatted as JSON

Documentation

Overview

Package caddy_oidc is a Caddy plugin for providing authentication and authorization using an OIDC IdP

Index

Constants

View Source
const (
	// SessionCtxKey is the context key used to store the authentication session object.
	// The context value is of type *Session.
	SessionCtxKey caddy.CtxKey = "oidc_session"
	// AuthMethodCtxKey is the context key used to store the authentication method used for the incoming request.
	// The context value is of type AuthMethod.
	AuthMethodCtxKey caddy.CtxKey = "oidc_auth_method"
)
View Source
const (
	// DefaultUsernameClaim is the default username claim to use for the BearerAuthenticator if none is specified.
	DefaultUsernameClaim = "sub"
)
View Source
const WellKnownOAuthProtectedResourcePath = "/.well-known/oauth-protected-resource"

WellKnownOAuthProtectedResourcePath is the path for the OAuth protected resource metadata endpoint.

Variables

View Source
var ErrAccessDenied = errors.New("access denied")

ErrAccessDenied is returned when the request is denied access.

View Source
var ErrInvalidAction = errors.New("not a valid Action")
View Source
var ErrInvalidEvaluationResult = errors.New("not a valid EvaluationResult")

Functions

func MatchWildcard

func MatchWildcard(pattern string, value string) bool

MatchWildcard matches a possible wildcard pattern against a value. Uses the same wildcard matching logic as caddyhttp.MatchHeader.

Types

type Action

type Action uint8

Action represents the possible actions to take when a rule is matched. ENUM(allow, deny)

const (
	// ActionAllow is a Action of type Allow.
	ActionAllow Action = iota
	// ActionDeny is a Action of type Deny.
	ActionDeny
)

func ParseAction added in v0.2.1

func ParseAction(name string) (Action, error)

ParseAction attempts to convert a string to a Action.

func (*Action) AppendText added in v0.2.1

func (x *Action) 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 (Action) IsValid added in v0.2.1

func (x Action) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (Action) MarshalText

func (x Action) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (Action) String

func (x Action) String() string

String implements the Stringer interface.

func (*Action) UnmarshalText

func (x *Action) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type App

type App struct {
	// Default contains the default / baseline OIDC configuration for this App.
	// The Default is used as a baseline configuration during caddyfile unmarshalling of named providers
	// and can be referenced directly in an OIDCMiddleware when a provider is not defined.
	Default   OIDCProviderModule             `json:"default"`
	Providers map[string]*OIDCProviderModule `json:"providers,omitempty"`
}

App holds configuration for all the named OIDC providers within a Caddy configuration.

func (*App) CaddyModule

func (*App) CaddyModule() caddy.ModuleInfo

func (*App) GetInheritedProvider added in v0.4.0

func (a *App) GetInheritedProvider(name string) (*OIDCProviderModule, error)

GetInheritedProvider returns the OIDCProviderModule for the given name. If the name is empty, then the default provider is returned. If the named provider is not configured, then an error is returned.

If a named provider is configured, then the baseline configuration is applied to the provider from the application global default provider configuration.

The caller must not modify the returned provider.

func (*App) Start

func (*App) Start() error

func (*App) Stop

func (*App) Stop() error

type ClaimMatch

type ClaimMatch struct {
	Name   string   `json:"name"`
	Values []string `json:"values"`
}

A ClaimMatch represents a claim name and a list of (optional) allowed values for that claim.

func (*ClaimMatch) MatchWithRepl added in v0.3.0

func (cm *ClaimMatch) MatchWithRepl(repl *caddy.Replacer, claims *gjson.Result) bool

MatchWithRepl matches the session claims against the claim match. Claims must be a valid gjson result containing a JSON object. If there are no values to match, MatchWithRepl returns true as long as the claim exists. Otherwise, at least one value must match. Both names and values of the ClaimMatch are pre-processed using the replacer.

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) Match

func (m *MatchAnonymous) Match(r *http.Request) bool

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 []authenticator.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) Match

func (m *MatchClaim) Match(r *http.Request) bool

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) Match

func (m *MatchUser) Match(r *http.Request) bool

func (*MatchUser) MatchWithError

func (m *MatchUser) MatchWithError(r *http.Request) (bool, error)

func (*MatchUser) UnmarshalCaddyfile

func (m *MatchUser) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

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 {
	OIDCProviderModule

	// Inherits is the name of a globally configured OIDC provider to inherit settings from.
	// The inherited configuration will be merged with the local configuration.
	Inherits string  `json:"inherits,omitempty"`
	Policies Ruleset `json:"policies"`
	// contains filtered or unexported fields
}

OIDCMiddleware is a middleware that authenticates and authorizes requests based on configured rules. It contains its own OIDC provider configuration. During provisioning, it applies the inherited baseline configuration to the local configuration.

func (*OIDCMiddleware) CaddyModule

func (mw *OIDCMiddleware) CaddyModule() caddy.ModuleInfo

func (*OIDCMiddleware) Provision

func (mw *OIDCMiddleware) Provision(ctx caddy.Context) error

Provision sets up the OIDCMiddleware by loading the configured OIDC provider and then provisioning the configured ruleset for the middleware. The named provider must be configured.

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(d *caddyfile.Dispenser) error

UnmarshalCaddyfile sets up the OIDCMiddleware from Caddyfile tokens.

	oidc [example] {

		allow|deny {
			...
		}
    }

func (*OIDCMiddleware) Validate

func (mw *OIDCMiddleware) Validate() error

Validate validates the configuration of the OIDCMiddleware.

type OIDCProviderModule

type OIDCProviderModule struct {
	Issuer                    string                                  `json:"issuer"`
	ClientID                  string                                  `json:"client_id"`
	ClientSecret              string                                  `json:"client_secret,omitempty"`
	Scope                     []string                                `json:"scope,omitempty"`
	Username                  string                                  `json:"username,omitempty"`
	Authenticators            *authenticator.Set                      `json:"authenticators,omitempty"`
	TLSInsecureSkipVerify     bool                                    `json:"tls_insecure_skip_verify,omitempty"`
	ProtectedResourceMetadata *ProtectedResourceMetadataConfiguration `json:"protected_resource_metadata,omitempty"`

	// TokenParams is an arbitrary map of additional key-values to set as URL parameters
	// when performing a code exchange. Values support Caddy placeholders such as
	// {file./path/to/secret} and {env.VAR} which are resolved at exchange time.
	TokenParams map[string]string `json:"token_params,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) (*Provider, error)

Create creates a Provider instance from this provider module configuration.

func (*OIDCProviderModule) Provision

func (m *OIDCProviderModule) Provision(ctx 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>
	authenticate <authenticator>
	tls_insecure_skip_verify
	scope [<scope>...]
	protected_resource <protected_resource>
}

func (*OIDCProviderModule) UnmarshalCaddyfileToken added in v0.4.0

func (m *OIDCProviderModule) UnmarshalCaddyfileToken(d *caddyfile.Dispenser) (bool, error)

func (*OIDCProviderModule) Validate

func (m *OIDCProviderModule) Validate() error

type ProtectedResourceMetadataConfiguration

type ProtectedResourceMetadataConfiguration struct {
	Disable  bool `json:"disable"`
	Audience bool `json:"audience,omitempty"`
}

ProtectedResourceMetadataConfiguration configures the protected resource metadata endpoint.

func (*ProtectedResourceMetadataConfiguration) UnmarshalCaddyfile

UnmarshalCaddyfile sets up the ProtectedResourceMetadataConfiguration from Caddyfile tokens.

protected_resource_metadata disable | {
	audience
}

type Provider added in v0.3.0

type Provider struct {
	Log               *zap.Logger
	Clock             func() time.Time
	Issuer            string
	UsernameClaim     string
	ProtectedResource *ProtectedResourceMetadataConfiguration
	Authenticators    authenticator.Set
	Discovery         *deferred.Result[*discoveryConfiguration]
}

Provider holds the built configuration for an OIDC provider and authentication logic.

func (*Provider) AuthCodeURL added in v0.3.0

func (pr *Provider) AuthCodeURL(ctx context.Context, state string, opts ...oauth2.AuthCodeOption) (string, error)

func (*Provider) Exchange added in v0.3.0

func (pr *Provider) Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)

func (*Provider) GetUsernameClaim added in v0.3.0

func (pr *Provider) GetUsernameClaim() string

func (*Provider) GetVerifier added in v0.3.0

func (pr *Provider) GetVerifier(ctx context.Context) (template.TokenVerifier, error)

func (*Provider) Now added in v0.3.0

func (pr *Provider) Now() time.Time

func (*Provider) ProtectedResourceMetadata added in v0.3.0

func (pr *Provider) 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 (*Provider) ServeHTTPOAuthProtectedResource added in v0.3.0

func (pr *Provider) 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 (*Provider) UserInfo added in v0.3.0

func (pr *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*oidc.UserInfo, error)

type Rule added in v0.2.1

type Rule struct {
	ID             string               `json:"id,omitempty"`
	Action         Action               `json:"action"`
	MatcherSetsRaw caddy.ModuleMap      `caddy:"namespace=http.matchers" json:"match,omitempty"`
	Matchers       caddyhttp.MatcherSet `json:"-"`
}

A Rule represents a single authorization rule with an associated action to take when matched with a request.

func (*Rule) MatchWithError added in v0.2.1

func (r *Rule) MatchWithError(req *http.Request) (bool, error)

MatchWithError returns true if the request matches the rule. Unlike caddyhttp.MatcherSets, an empty matcher set never matches a request.

func (*Rule) Provision added in v0.2.1

func (r *Rule) Provision(ctx caddy.Context) error

Provision this rule by loading the matcher modules from MatcherSetsRaw. Each loaded module must be a RequestMatcher or RequestMatcherWithError.

type RuleEvaluation added in v0.2.1

type RuleEvaluation struct {
	Result EvaluationResult `json:"result"`
	// The optional ID of the matched rule.
	// If the result is EvaluationResultImplicitDeny, this field is always empty.
	RuleID string `json:"rule_id"`
}

RuleEvaluation represents the result of evaluating a ruleset.

type Ruleset added in v0.2.1

type Ruleset []*Rule

A Ruleset is a set of authorization rules.

func (*Ruleset) ContainsAllow added in v0.2.1

func (rules *Ruleset) ContainsAllow() bool

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) (RuleEvaluation, 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) Provision added in v0.2.1

func (rules *Ruleset) Provision(ctx caddy.Context) error

Provision all rules in the set.

func (*Ruleset) UnmarshalCaddyfile added in v0.2.1

func (rules *Ruleset) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

UnmarshalCaddyfile sets up the Ruleset from Caddyfile tokens. Syntax:

allow|deny <rule_id> {
	...
}

func (*Ruleset) UnmarshalCaddyfileToken added in v0.4.0

func (rules *Ruleset) UnmarshalCaddyfileToken(d *caddyfile.Dispenser) (bool, error)

func (*Ruleset) Validate added in v0.2.1

func (rules *Ruleset) Validate() error

Validate checks if the set contains at least one ActionAllow rule.

Directories

Path Synopsis
Package authenticator provides a modular plugin interface for providing authentication mechanisms to the caddy-oidc plugin.
Package authenticator provides a modular plugin interface for providing authentication mechanisms to the caddy-oidc plugin.
internal
baseline
Package baseline provides a mechanism for applying baseline overrides to Go structs
Package baseline provides a mechanism for applying baseline overrides to Go structs
deferred
Package deferred provides a simple way to defer a function call in a separate goroutine and allow multiple callers to wait for the result.
Package deferred provides a simple way to defer a function call in a separate goroutine and allow multiple callers to wait for the result.
pkgtest
Package pkgtest provides utilities for testing.
Package pkgtest provides utilities for testing.
Package request provides utilities for working with HTTP requests.
Package request provides utilities for working with HTTP requests.
Package session contains types and functions for working with authentication sessions.
Package session contains types and functions for working with authentication sessions.
Package template is an internal package that provides primitives for Caddy replacer replaced values.
Package template is an internal package that provides primitives for Caddy replacer replaced values.

Jump to

Keyboard shortcuts

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