caddy_oidc

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2026 License: MIT Imports: 27 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 configure the OIDC provider. An example minimum configuration is shown below.

{
    oidc example {
        issuer https://accounts.google.com
        client_id < client_id >
        secret_key {env.OIDC_SECRET_KEY}
    }
}

Each route then uses the oidc directive to configure the route using the named provider

example.com {
    oidc example {
        allow {
            user *
        }
    }
    reverse_proxy localhost:8080
}

Global Directive

Option Description Default
issuer The OIDC issuer URL
client_id The OIDC client ID
secret_key A secret key used to sign cookies with, must be either 32 or 64 bytes long
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
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. sub
claim (optional) A list of claims to include in the session. Used for request authorization. Any access policy rules that use a claim must be configured here.
cookie (optional) Configures the cookie used to store the authentication state.
protected_resource_metadata (optional) Configure or disable RFC9728 support.

Cookie configuration is used to control how the authentication session cookie is set. The session cookie is a signed cookie containing minimal state about the user's authentication.

Option Description
name The name of the cookie.
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.

The default configuration is shown below.

cookie {
    name caddy
    same_site lax
    path /
}
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. Requests are authenticated according to the configured OIDC provider and then authorized according to access policy rules configured in the directive.

The handler directive must contain at least one allow rule.

# Allow any valid authenticated user

example.com {
    oidc example {
        allow {
            user *
        }
    }
    reverse_proxy localhost:8080
}

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 requests.

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 must be configured in the oidc directive claim option.

# 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

  • none - The request is not authenticated
  • cookie - The request was authenticated using a session cookie
  • bearer - The request was authenticated using a bearer JWT token
# 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 none, cookie or bearer
http.auth.user.claim.* Set for each extracted claim from the claim option of the global directive
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

Index

Constants

View Source
const (
	SessionCtxKey    caddy.CtxKey = "oidc_session"
	AuthMethodCtxKey caddy.CtxKey = "oidc_auth_method"
)
View Source
const (
	DefaultRedirectUriPath = "/oauth2/callback"
	DefaultUsernameClaim   = "sub"
)
View Source
const Leeway = time.Second * 5
View Source
const ModuleID = "oidc"
View Source
const WellKnownOAuthProtectedResourcePath = "/.well-known/oauth-protected-resource"

Variables

View Source
var (
	AnonymousSession = &Session{
		Anonymous: true,
		Claims:    json.RawMessage(`{}`),
	}
)
View Source
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.

View Source
var DefaultCookieOptions = Cookies{
	Name:     "caddy",
	SameSite: SameSite{http.SameSiteLaxMode},
	Insecure: false,
	Domain:   "",
	Path:     "/",
}
View Source
var ErrAccessDenied = errors.New("access denied")
View Source
var ErrInvalidAction = errors.New("not a valid Action")
View Source
var ErrInvalidAuthMethod = errors.New("not a valid AuthMethod")
View Source
var ErrInvalidEvaluationResult = errors.New("not a valid EvaluationResult")
View Source
var ErrNoAuthorization = errors.New("no authorization provided")

Functions

func ClientIP

func ClientIP(r *http.Request) (netip.Addr, error)

ClientIP gets the real client IP address from the request using the same method Caddy would

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.

func RequestUrl

func RequestUrl(r *http.Request) *url.URL

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

func ShouldStartLogin(r *http.Request) bool

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)

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 {
	Providers map[string]*OIDCProviderModule `json:"providers,omitempty"`
	// contains filtered or unexported fields
}

func (*App) CaddyModule

func (*App) CaddyModule() caddy.ModuleInfo

func (*App) Provision

func (a *App) Provision(ctx caddy.Context) error

func (*App) Start

func (*App) Start() error

func (*App) Stop

func (*App) Stop() error

func (*App) Validate

func (a *App) Validate() error

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 CSRFToken

type CSRFToken struct {
	PKCEVerifier string `json:"v"`
	RedirectURI  string `json:"r"`
}

type ClaimMatch

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

type ClaimsDecoder

type ClaimsDecoder interface {
	Claims(v any) error
}

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

func (o *Cookies) New(value string) *http.Cookie

func (*Cookies) UnmarshalCaddyfile

func (o *Cookies) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

UnmarshalCaddyfile sets up the Cookies from Caddyfile tokens.

 syntax
 cookie <name> | {
	name <name>
	same_site <same_site>
	insecure
	domain <domain>
	path <path>
 }

func (*Cookies) Validate

func (o *Cookies) Validate() error

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.

func (*DeferredResult[T]) Get

func (d *DeferredResult[T]) Get(ctx context.Context) (T, error)

Get blocks until the background process is finished or the context is canceled.

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 []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 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) Provision

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

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

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

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

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

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

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

func (*Ruleset) UnmarshalCaddyfile added in v0.2.1

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

func (*Ruleset) Validate added in v0.2.1

func (rules *Ruleset) Validate() error

type SameSite

type SameSite struct {
	http.SameSite
}

func (*SameSite) MarshalText

func (s *SameSite) MarshalText() ([]byte, error)

func (*SameSite) String

func (s *SameSite) String() string

func (*SameSite) UnmarshalCaddyfile

func (s *SameSite) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

func (*SameSite) UnmarshalText

func (s *SameSite) UnmarshalText(text []byte) error

func (*SameSite) Validate

func (s *SameSite) Validate() error

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

func (s *Session) Expires() time.Time

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

func (*Session) ValidateClock

func (s *Session) ValidateClock(now time.Time) error

ValidateClock checks if the session is still valid. If the session has expired, then it returns an oidc.TokenExpiredError

type UserInfoClient

type UserInfoClient interface {
	UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*oidc.UserInfo, error)
}

Jump to

Keyboard shortcuts

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