Key Auth (密钥认证) 中间件

Key Auth 中间件提供了一个基于密钥的验证方式。

  • 对于有效密钥,它将调用下一个处理程序。
  • 对于无效密钥,它会发送 “401 - Unauthorized” 响应。
  • 对于丢失密钥,它发送 “400 - Bad Request” 响应。

用法

  1. e.Use(middleware.KeyAuth(func(key string) bool {
  2. return key == "valid-key"
  3. }))

自定义配置

用法

  1. e := echo.New()
  2. e.Use(middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{
  3. KeyLookup: "query:api-key",
  4. }))

配置

  1. // KeyAuthConfig defines the config for KeyAuth middleware.
  2. KeyAuthConfig struct {
  3. // Skipper defines a function to skip middleware.
  4. Skipper Skipper
  5. // KeyLookup is a string in the form of "<source>:<name>" that is used
  6. // to extract key from the request.
  7. // Optional. Default value "header:Authorization".
  8. // Possible values:
  9. // - "header:<name>"
  10. // - "query:<name>"
  11. KeyLookup string `json:"key_lookup"`
  12. // AuthScheme to be used in the Authorization header.
  13. // Optional. Default value "Bearer".
  14. AuthScheme string
  15. // Validator is a function to validate key.
  16. // Required.
  17. Validator KeyAuthValidator
  18. }

默认配置

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