package middleware import ( "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) // KeyAuthValidator defines a function to validate KeyAuth credentials. type KeyAuthValidator = middleware.KeyAuthValidator // KeyAuthErrorHandler defines a function which is executed for an invalid key. type KeyAuthErrorHandler = middleware.KeyAuthErrorHandler // KeyAuthConfig defines the config for KeyAuth middleware. type KeyAuthConfig struct { Skipper Skipper // KeyLookup is a string in the form of ":" or ":,:" that is used // to extract key from the request. // Optional. Default value "header:Authorization". // Possible values: // - "header:" or "header::" // `` is argument value to cut/trim prefix of the extracted value. This is useful if header // value has static prefix like `Authorization: ` where part that we // want to cut is ` ` note the space at the end. // In case of basic authentication `Authorization: Basic ` prefix we want to remove is `Basic `. // - "query:" // - "form:" // - "cookie:" // Multiple sources example: // - "header:Authorization,header:X-Api-Key" KeyLookup string // AuthScheme to be used in the Authorization header. // Optional. Default value "Bearer". AuthScheme string // Validator is a function to validate key. // Required. Validator KeyAuthValidator // ErrorHandler defines a function which is executed for an invalid key. // It may be used to define a custom error. ErrorHandler KeyAuthErrorHandler // ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandler decides to // ignore the error (by returning `nil`). // This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality. // In that case you can use ErrorHandler to set a default public key auth value in the request context // and continue. Some logic down the remaining execution chain needs to check that (public) key auth value then. ContinueOnIgnoredError bool } // DefaultKeyAuthConfig is the default KeyAuth middleware config. var DefaultKeyAuthConfig = KeyAuthConfig{ Skipper: DefaultSkipper, KeyLookup: "header:" + echo.HeaderAuthorization, AuthScheme: "Bearer", } func (a *KeyAuthConfig) ToMiddleware() echo.MiddlewareFunc { return middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{ Skipper: a.Skipper, KeyLookup: a.KeyLookup, AuthScheme: a.AuthScheme, Validator: a.Validator, ErrorHandler: a.ErrorHandler, ContinueOnIgnoredError: a.ContinueOnIgnoredError, }) } func KeyAuth() echo.MiddlewareFunc { return DefaultKeyAuthConfig.ToMiddleware() }