Key Auth

Key auth middleware provides a key based authentication.

  • For valid key it calls the next handler.
  • For invalid key, it sends “401 - Unauthorized” response.
  • For missing key, it sends “400 - Bad Request” response.

Usage

  1. e.Use(middleware.KeyAuth(func(key string, c echo.Context) (bool, error) {
  2. return key == "valid-key", nil
  3. }))

Custom Configuration

Usage

  1. e := echo.New()
  2. e.Use(middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{
  3. KeyLookup: "query:api-key",
  4. Validator: func(key string, c echo.Context) (bool, error) {
  5. return key == "valid-key", nil
  6. },
  7. }))

Configuration

  1. KeyAuthConfig struct {
  2. // Skipper defines a function to skip middleware.
  3. Skipper Skipper
  4. // KeyLookup is a string in the form of "<source>:<name>" that is used
  5. // to extract key from the request.
  6. // Optional. Default value "header:Authorization".
  7. // Possible values:
  8. // - "header:<name>"
  9. // - "query:<name>"
  10. // - "cookie:<name>"
  11. // - "form:<name>"
  12. KeyLookup string `yaml:"key_lookup"`
  13. // AuthScheme to be used in the Authorization header.
  14. // Optional. Default value "Bearer".
  15. AuthScheme string
  16. // Validator is a function to validate key.
  17. // Required.
  18. Validator KeyAuthValidator
  19. // ErrorHandler defines a function which is executed for an invalid key.
  20. // It may be used to define a custom error.
  21. ErrorHandler KeyAuthErrorHandler
  22. }

Default Configuration

  1. DefaultKeyAuthConfig = KeyAuthConfig{
  2. Skipper: DefaultSkipper,
  3. KeyLookup: "header:" + echo.HeaderAuthorization,
  4. AuthScheme: "Bearer",
  5. }