### Example Configuration Validation Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Demonstrates validating an AuthnMiddleware configuration. This example assumes the portal has been set during provisioning. ```go m := &AuthnMiddleware{ RouteMatcher: "*", PortalName: "default", // portal must be set during provisioning } err := m.Validate() if err != nil { log.Fatal("Invalid configuration:", err) } ``` -------------------------------- ### Start App Method Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/app.md Starts the App. Called by Caddy after provisioning. This method is expected to return nil on success. ```go func (app App) Start() error { // ... implementation details ... return nil } ``` -------------------------------- ### Start Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/app.md Starts the App. This method is called by Caddy after the provisioning process is complete. ```APIDOC ## Start ### Description Starts the App. Called by Caddy after provisioning. ### Method `func (app App) Start() error` ### Parameters None ### Return type `error` Returns nil ### Example ```go app := &App{} err := app.Start() ``` ``` -------------------------------- ### Install Dependencies with Make Source: https://github.com/greenpau/caddy-security/blob/main/CONTRIBUTING.md Navigates into the caddy-security directory and installs project dependencies using the make command. ```bash cd caddy-security make dep ``` -------------------------------- ### AuthzMiddleware Example Usage Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/types.md Example of how to instantiate and configure an AuthzMiddleware object with a specific route and gatekeeper policy. ```go m := &AuthzMiddleware{ RouteMatcher: "/api/*", GatekeeperName: "api-policy", } ``` -------------------------------- ### Example Usage of CaddyModule Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Demonstrates how to retrieve the Caddy module information for AuthnMiddleware. ```go info := AuthnMiddleware{}.CaddyModule() // info.ID == "http.handlers.authenticator" ``` -------------------------------- ### Example Provisioning Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Shows how to provision an AuthnMiddleware instance with a specified portal name. Handle potential errors during provisioning. ```go m := &AuthnMiddleware{ PortalName: "default", } err := m.Provision(ctx) if err != nil { log.Fatal("Failed to provision authenticator:", err) } ``` -------------------------------- ### Handle HTTP Request with Caddy Utilities Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/utilities.md Example of handling an HTTP request using Caddy's replacer and utility functions to get a request ID and perform replacements. Ensure necessary imports are included. ```go package main import ( "context" "log" "net/http" "github.com/caddyserver/caddy/v2" "github.com/greenpau/caddy-security/pkg/util" ) func handleRequest(w http.ResponseWriter, r *http.Request) { // Get or generate request ID requestID := util.GetRequestID(r) // Perform replacements repl := caddy.NewReplacer() appName, replaced, err := util.FindReplace(repl, "{env.APP_NAME}") if err != nil { log.Printf("Request %s: Replacement error: %v", requestID, err) http.Error(w, "Configuration error", http.StatusInternalServerError) return } w.Header().Set("X-Request-ID", requestID) w.Header().Set("X-App-Name", appName) w.WriteHeader(http.StatusOK) } ``` -------------------------------- ### Example ServeHTTP Usage Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Shows how to call the ServeHTTP method to process an HTTP request for authentication. Log any authentication failures. ```go m := &AuthnMiddleware{PortalName: "default"} // In HTTP handler err := m.ServeHTTP(w, r, nil) if err != nil { log.Error("Authentication failed:", err) } ``` -------------------------------- ### Update Auth Portal Cookie Configuration Examples Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/configuration-parsers.md Examples of updating authentication portal cookie configurations using a helper function. Demonstrates applying settings to the default domain or a specific domain. ```go // 2 args: apply to default domain updateAuthPortalCookieConfig(portal, "default", "path", "/auth") // 3 args: apply to specific domain updateAuthPortalCookieConfig(portal, "example.com", "lifetime", "3600") ``` -------------------------------- ### Caddy Security Configuration Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/app.md Example JSON configuration for the Caddy security module, demonstrating settings for authentication portals and authorization policies. ```json { "security": { "config": { "authentication_portals": [ { "name": "default", "ui": { "templates": {} } } ], "authorization_policies": [ { "name": "default" } ] }, "secrets_managers": [] } } ``` -------------------------------- ### Caddyfile Authentication Portal Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/configuration-parsers.md Example of an authentication portal block in Caddyfile syntax. This demonstrates how to specify crypto keys, cookie domains, and UI elements. ```caddyfile authentication portal my-portal { crypto key sign-verify secret-key cookie domain example.com ui { logo_url /logo.png } } ``` -------------------------------- ### Caddyfile Authentication UI Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/configuration-parsers.md Example of a UI configuration block within an authentication portal in Caddyfile syntax. This shows how to specify login templates, logo URLs, custom CSS, and role-based access to settings. ```caddyfile ui { template login /templates/login.html logo_url /assets/logo.png custom css path /assets/style.css allow settings for role admin } ``` -------------------------------- ### GetConfig Method Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/secrets-manager.md Example implementation of the GetConfig method. This method should return a map containing at least an 'id' and 'driver' field to identify the secrets manager. ```go func (sm *MySecretsManager) GetConfig(ctx context.Context) map[string]interface{} { return map[string]interface{}{ "id": "vault", "driver": "hashicorp-vault", "address": sm.vaultAddr, } } ``` -------------------------------- ### GetSecret Method Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/secrets-manager.md Example implementation of the GetSecret method. This method is responsible for retrieving all secrets managed by the plugin. ```go func (sm *MySecretsManager) GetSecret(ctx context.Context) (map[string]interface{}, error) { secrets := make(map[string]interface{}) // Retrieve all secrets from backing store return secrets, nil } ``` -------------------------------- ### Authentication Portal with Environment Variable Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/configuration.md Example of configuring an authentication portal using an environment variable for the signing key. ```caddyfile authentication portal default { crypto key sign-verify {env.SIGNING_KEY} } ``` -------------------------------- ### Vault Secrets Manager Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/configuration.md Example configuration for the Vault secrets manager, including address, token, and path. ```caddyfile secrets vault { id vault address https://vault.example.com token path secret/data } ``` -------------------------------- ### Caddyfile Syntax Examples Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Illustrates the correct Caddyfile syntax for the 'authenticate' directive, showing variations for default and specific route matchers. ```caddyfile authenticate * with default authenticate /admin/* with admin-portal ``` -------------------------------- ### GetSecretByKey Method Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/secrets-manager.md Example implementation of the GetSecretByKey method. This method retrieves a specific secret value using its key from the backing store. ```go func (sm *MySecretsManager) GetSecretByKey(ctx context.Context, key string) (interface{}, error) { // Retrieve specific secret by key value, err := sm.vault.Get(ctx, key) if err != nil { return nil, fmt.Errorf("failed to get secret %s: %w", key, err) } return value, nil } ``` -------------------------------- ### Example 'authenticate' Directive in Caddyfile Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/http-integration.md Demonstrates the usage of the 'authenticate' directive within a Caddyfile configuration to protect a route. ```caddyfile :80 { authenticate * with default respond "Protected" } ``` -------------------------------- ### Example Log Entry for Authorization Failure Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/errors.md This is an example of a detailed log entry for an authorization failure, including request context. ```log Authorization failed: src_ip=192.168.1.100, email=user@example.com, sub=user123, policy denied access for path=/admin ``` -------------------------------- ### Secret Reference Syntax Examples Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/secrets-manager.md Secrets are referenced in configuration using the `secrets::` format. Examples show how to reference secrets from different managers. ```plaintext secrets:vault:database-password ``` ```plaintext secrets:aws-secrets:api-key ``` -------------------------------- ### Add Arguments to Authorization Error Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/errors.md This example demonstrates how to create a more informative authorization error by adding contextual arguments. This is useful for debugging and logging. ```go err := errors.ErrAuthorizationFailed.WithArgs( getAuthorizationDetails(r, ar), // "src_ip=..., email=..., sub=..." err, // Underlying error ) ``` -------------------------------- ### Complete Caddy Security Configuration Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/configuration.md A comprehensive Caddyfile demonstrating various security configurations including LDAP credentials, local identity stores, OAuth providers, authentication portals, and authorization policies with environment variable usage. ```caddyfile { security { # Credentials credentials ldap { domain example.com username admin password {env.LDAP_PASSWORD} } # Local identity store local identity store users { realms example.com } # OAuth identity provider oauth identity provider google { realm google driver google client_id {env.GOOGLE_CLIENT_ID} client_secret secrets:vault:google-secret scopes openid email profile } # Authentication portal authentication portal default { crypto key sign-verify {env.SIGNING_KEY} cookie domain example.com cookie path / cookie lifetime 3600 cookie samesite lax ui { logo_url https://example.com/logo.png logo_description "My Company" } enable source ip tracking enable identity store users enable identity provider google validate source address } # Authorization policy authorization policy default { crypto key verify default {env.PUBLIC_KEY} allow request path /api action GET role user allow request path /admin action * role admin deny request path /internal action * role guest bypass uri exact /health bypass uri prefix /.well-known enable jwt validation inject header X-User-ID sub inject header X-User-Roles roles } } } :80 { authenticate * with default basicauth /api/* { authorize * with default } respond "Authenticated and authorized" } ``` -------------------------------- ### Get Caddy Module Info Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authz-middleware.md Returns metadata for the authorization middleware Caddy module. ```go func (AuthzMiddleware) CaddyModule() caddy.ModuleInfo ``` ```go info := AuthzMiddleware{}.CaddyModule() // info.ID == "http.authentication.providers.authorizer" ``` -------------------------------- ### Example 'authorize' Directive within 'basicauth' in Caddyfile Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/http-integration.md Shows how to use the 'authorize' directive nested within 'basicauth' in a Caddyfile to apply specific policies to a route. ```caddyfile :80 { basicauth /api/* { authorize * with api-policy } respond "Authorized" } ``` -------------------------------- ### Caddyfile Route Matching Examples Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/http-integration.md Configure route matching for the 'authenticate' directive to apply authentication to specific URL paths. The '*' matcher applies to all routes, '/path*' applies to a prefix, and '/path' applies to an exact match. ```caddyfile authenticate * with portal authenticate /admin* with admin-portal authenticate /api/* with api-portal ``` -------------------------------- ### Create Authorization Failed Error Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/http-integration.md Example of creating a specific authorization failed error, incorporating audit details and a reason for denial. ```go err := errors.ErrAuthorizationFailed.WithArgs( getAuthorizationDetails(r, ar), // Audit information "policy denied access", // Error reason ) ``` -------------------------------- ### Get Caddy Module Metadata Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Returns Caddy module metadata for the AuthnMiddleware, including its ID and constructor. ```go func (AuthnMiddleware) CaddyModule() caddy.ModuleInfo ``` -------------------------------- ### Configure Authorization with Basic Auth Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authz-middleware.md Use the `authorize` directive within `basicauth` to apply an authorization policy to a specific route. This example applies the `api-policy` to requests matching `/api/*`. ```caddyfile :80 { # Use authorization with basicauth basicauth /api/* { authorize * with api-policy } respond "Authorized" } ``` -------------------------------- ### Caddyfile Malformed Directive Example Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/errors.md Illustrates a Caddyfile syntax error due to a missing 'with' keyword in the 'authenticate' directive. Use correct syntax with the 'with' keyword for proper configuration. ```caddyfile # Missing 'with' keyword - triggers error authenticate /admin* admin-portal # Correct syntax authenticate /admin* with admin-portal ``` -------------------------------- ### API Reference Overview Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/MANIFEST.txt This section provides an overview of the API reference documentation, guiding users to specific files for detailed information on different components of the Caddy Security module. ```APIDOC ## API Reference This section details the API surfaces available for the Caddy Security module. It is organized into several markdown files, each focusing on a specific aspect of the module's functionality. ### Key API Reference Files: - **`api-reference/app.md`**: Documentation for the main application components. - **`api-reference/authn-middleware.md`**: Details on authentication middleware. - **`api-reference/authz-middleware.md`**: Details on authorization middleware. - **`api-reference/secrets-manager.md`**: Information on the secrets management component. - **`api-reference/utilities.md`**: Documentation for utility functions. - **`api-reference/configuration-parsers.md`**: Information on configuration parsing. - **`api-reference/http-integration.md`**: Details on HTTP integration aspects. ``` -------------------------------- ### Configure Authorization for Multiple Routes Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authz-middleware.md Apply different authorization policies to distinct routes using nested `basicauth` blocks within `route` directives. This example separates policies for `/api/*` and `/admin/*`. ```caddyfile :80 { # Multiple routes with different policies route /api/* { basicauth { authorize * with api-policy } respond "API response" } route /admin/* { basicauth { authorize * with admin-policy } respond "Admin response" } } ``` -------------------------------- ### Vault Secrets Manager Implementation Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/secrets-manager.md An example implementation of a `VaultSecretsManager` struct in Go. This includes methods for retrieving configuration, fetching all secrets, and fetching a specific secret by key from Vault. ```go type VaultSecretsManager struct { ID string Address string Token string } func (vsm *VaultSecretsManager) GetConfig(ctx context.Context) map[string]interface{} { return map[string]interface{}{ "id": vsm.ID, "driver": "vault", "address": vsm.Address, } } func (vsm *VaultSecretsManager) GetSecret(ctx context.Context) (map[string]interface{}, error) { // Fetch all secrets from Vault return vsm.fetchAllFromVault(ctx) } func (vsm *VaultSecretsManager) GetSecretByKey(ctx context.Context, key string) (interface{}, error) { // Fetch specific secret from Vault return vsm.fetchFromVault(ctx, key) } ``` -------------------------------- ### Create Development Directory Source: https://github.com/greenpau/caddy-security/blob/main/CONTRIBUTING.md Sets up a dedicated directory for local development and navigates into it. ```bash mkdir -p ~/tmpdev cd ~/tmpdev ``` -------------------------------- ### Provision App Method Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/app.md Initializes the security app during Caddy startup. It provisions the logger, loads secrets manager plugins, validates configuration, and creates the internal authcrunch server. Handle provisioning errors by checking the returned error. ```go func (app *App) Provision(ctx caddy.Context) error { // ... implementation details ... return nil } ``` -------------------------------- ### New App Constructor Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/app.md Creates and returns a new instance of the App type. ```go func New() *App { return new(App) } ``` -------------------------------- ### Build Project with Make Source: https://github.com/greenpau/caddy-security/blob/main/CONTRIBUTING.md Compiles the project using local source code, creating a binary in the bin/ directory. ```bash make ``` -------------------------------- ### Provision Method Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Initializes the AuthnMiddleware, retrieving the security app and authentication portal configuration. ```APIDOC ## Provision Method ```go func (m *AuthnMiddleware) Provision(ctx caddy.Context) error ``` Initializes the middleware. Retrieves the security app from Caddy context and obtains the authentication portal configuration by name. **Parameters**: | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | ctx | caddy.Context | Yes | Caddy context for module initialization | **Return type**: `error` Returns nil on success, error if: - Security app is not found in Caddy context - Portal name cannot be resolved - Portal does not exist in security app configuration **Throws**: | Error | Condition | |-------|-----------| | "security app is nil" | Security app module not loaded | | "security app config is nil" | App configuration missing | | "authentication portal not found" | Named portal does not exist | **Example**: ```go m := &AuthnMiddleware{ PortalName: "default", } err := m.Provision(ctx) if err != nil { log.Fatal("Failed to provision authenticator:", err) } ``` ``` -------------------------------- ### App Configuration JSON Marshaling Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/types.md Demonstrates how to marshal an App configuration to JSON with indentation. Ensure the App and its Config are properly initialized. ```go // App with minimal configuration app := &App{ Config: authcrunch.NewConfig(), } data, _ := json.MarshalIndent(app, "", " ") ``` -------------------------------- ### Provision Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authz-middleware.md Initializes the middleware. Retrieves the security app and obtains the gatekeeper policy by name. ```APIDOC ## Provision ### Description Initializes the middleware. Retrieves the security app and obtains the gatekeeper policy by name. ### Parameters #### Path Parameters - **ctx** (caddy.Context) - Required - Caddy context for module initialization ### Return type `error` Returns nil on success, error if: - Security app is not found - Gatekeeper name cannot be resolved - Gatekeeper policy does not exist ### Throws - **"security app is nil"** - Security app module not loaded - **"security app config is nil"** - App configuration missing - **"authorization policy not found"** - Named gatekeeper/policy does not exist ### Example ```go m := &AuthzMiddleware{ GatekeeperName: "default", } err := m.Provision(ctx) if err != nil { log.Fatal("Failed to provision authorizer:", err) } ``` ``` -------------------------------- ### New AuthnMiddleware Constructor Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Creates and returns a new instance of AuthnMiddleware. ```go func New() *AuthnMiddleware { return new(AuthnMiddleware) } ``` -------------------------------- ### Provision Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/app.md Initializes the security app during Caddy startup. It handles provisioning the logger, loading secrets manager plugins, validating configuration, and creating the internal authcrunch server. ```APIDOC ## Provision ### Description Initializes the security app. Called by Caddy during startup. Provisions the logger, loads secrets manager plugins, validates configuration, and creates the internal authcrunch server. ### Method `func (app *App) Provision(ctx caddy.Context) error` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (caddy.Context) - Required - Caddy context for app initialization ### Return type `error` Returns an error if provisioning fails, nil on success ### Throws - `error` - secrets manager plugin fails to load - `error` - configuration validation fails - `error` - server initialization fails ### Example ```go app := &App{ Config: authcrunch.NewConfig(), } err := app.Provision(ctx) if err != nil { // Handle provisioning error } ``` ``` -------------------------------- ### App Type Methods Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/MANIFEST.txt The App type provides core lifecycle management for the security module within Caddy. It includes methods for module registration, provisioning, starting, and stopping. ```APIDOC ## App Type Methods ### CaddyModule() **Description**: Registers the App module with Caddy. ### Provision() **Description**: Provisions the App module, setting up its internal state. ### Start() **Description**: Starts the App module, enabling its functionality. ### Stop() **Description**: Stops the App module, gracefully shutting down its operations. ``` -------------------------------- ### Provision AuthnMiddleware Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Initializes the AuthnMiddleware by retrieving the security app and authentication portal from the Caddy context. Ensure the security app is loaded and the portal exists. ```go func (m *AuthnMiddleware) Provision(ctx caddy.Context) error ``` -------------------------------- ### Configure Messaging Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/configuration.md Set up messaging configurations, including backend type, server address, port, username, and password. ```caddyfile messaging { local { backend server port username password } } ``` -------------------------------- ### Get Request ID from HTTP Request Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/utilities.md Retrieves an existing request ID from the HTTP request headers or context, or generates a new UUID if none is found. Use this to ensure consistent request tracking. ```go requestID := GetRequestID(r) log.Infof("Request %s from %s", requestID, r.RemoteAddr) ``` -------------------------------- ### Create Configuration Path Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/configuration-parsers.md Use mkcp to construct a configuration path by joining string parts with dots. This is useful for defining nested configuration keys. ```Go func mkcp(parts ...string) string ``` ```Go path := mkcp("security", "authentication", "portal", "crypto") // Returns: "security.authentication.portal.crypto" ``` -------------------------------- ### mkcp Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/configuration-parsers.md Creates a configuration path string by joining multiple string parts with dots. ```APIDOC ## mkcp ### Description Makes a config path by joining parts with dots. ### Signature ```go func mkcp(parts ...string) string ``` ### Parameters - **parts** (...string) - Variable number of strings to join. ### Return type - `string` - The joined configuration path. ### Example ```go path := mkcp("security", "authentication", "portal", "crypto") // Returns: "security.authentication.portal.crypto" ``` ``` -------------------------------- ### Basic Authentication Portal Syntax Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/configuration.md This is the general syntax for configuring an authentication portal in Caddyfile. It outlines the various directives and their possible sub-directives for comprehensive control. ```caddyfile authentication portal { crypto key sign-verify cookie domain cookie path cookie lifetime cookie samesite cookie insecure ui { template logo_url logo_description custom css path custom js path custom html header path static_asset allow settings for role } enable source ip tracking enable admin api enable identity store enable identity provider enable sso provider enable user registration validate source address transform user trust [login|logout] redirect uri domain [exact|partial|prefix|suffix|regex] path [exact|partial|prefix|suffix|regex] set cookie name } ``` -------------------------------- ### Wrapping AuthzMiddleware for Caddy Authentication Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/http-integration.md Illustrates the process of wrapping an AuthzMiddleware instance to be used as a provider within Caddy's authentication system. ```go return caddyauth.Authentication{ ProvidersRaw: caddy.ModuleMap{ authzPluginName: caddyconfig.JSON(m, nil), }, }, nil ``` -------------------------------- ### New AuthzMiddleware Constructor Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authz-middleware.md Provides a constructor function to create a new instance of AuthzMiddleware. This is used to initialize the middleware with default settings. ```go func New() *AuthzMiddleware { return new(AuthzMiddleware) } ``` -------------------------------- ### Provision Authorization Middleware Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authz-middleware.md Initializes the authorization middleware, retrieving the security app and gatekeeper policy. Ensure the security app module is loaded and the gatekeeper policy is correctly named. ```go m := &AuthzMiddleware{ GatekeeperName: "default", } err := m.Provision(ctx) if err != nil { log.Fatal("Failed to provision authorizer:", err) } ``` -------------------------------- ### New AuthnMiddleware Constructor Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/authn-middleware.md Creates and returns a new instance of AuthnMiddleware. ```APIDOC ## New AuthnMiddleware Constructor ```go func New() *AuthnMiddleware { return new(AuthnMiddleware) } ``` ``` -------------------------------- ### Handle Provisioning Errors in Go Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/errors.md Use this pattern to handle errors during the provisioning and validation of an authenticator middleware. ```go m := &AuthnMiddleware{ PortalName: "default", } err := m.Provision(ctx) if err != nil { log.Error("Failed to provision authenticator:", err) return err } err = m.Validate() if err != nil { log.Error("Invalid authenticator configuration:", err) return err } ``` -------------------------------- ### ServeHTTP Method for AuthnMiddleware Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/api-reference/http-integration.md Handles incoming HTTP requests for authentication. It generates a request ID, wraps the request, and calls the portal's ServeHTTP method. The portal handles the response directly. ```go func (m *AuthnMiddleware) w http.ResponseWriter, r *http.Request, _ caddyhttp.Handler, ) error ``` ```go rr := requests.NewRequest() rr.ID = util.GetRequestID(r) return m.portal.ServeHTTP(r.Context(), w, r, rr) ``` ```go // In HTTP handler chain err := m.ServeHTTP(w, r, next) if err != nil { log.Error("Authentication error:", err) return err } // If no error, response already written by portal ``` -------------------------------- ### Configure LDAP Identity Store Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/configuration.md Sets up an identity store using LDAP for user authentication. Requires specifying server details, bind credentials, and user/group search parameters. ```caddyfile ldap identity store { realm servers bindn bindpw userdn userattr mailattrname groupdn groupattr } ``` -------------------------------- ### Configure Credentials Source: https://github.com/greenpau/caddy-security/blob/main/_autodocs/configuration.md Define credentials for authentication, specifying domain, username, and password. ```caddyfile credentials