Basic Auth
Basic Auth 中间件提供 HTTP Basic 认证。
- 对于有效凭据,它会调用下一个处理函数。
- 对于缺失或无效凭据,它会发送
401 Unauthorized响应。
所有核心中间件都位于 middleware 包中:
import "github.com/labstack/echo/v5/middleware"e.Use(middleware.BasicAuth(func(c *echo.Context, username, password string) (bool, error) { // Use a constant time comparison to prevent timing attacks. if subtle.ConstantTimeCompare([]byte(username), []byte("joe")) == 1 && subtle.ConstantTimeCompare([]byte(password), []byte("secret")) == 1 { return true, nil } return false, nil}))e.Use(middleware.BasicAuthWithConfig(middleware.BasicAuthConfig{}))BasicAuthConfig · github.com/labstack/echo/v5@5196b9b
字段说明由英文源码注释生成。
| 字段 | 类型 | 说明 | 源码 |
|---|---|---|---|
Skipper | Skipper | Skipper defines a function to skip middleware. | L23 |
Validator | BasicAuthValidator | Validator is a function to validate BasicAuthWithConfig credentials. Note: if request contains multiple basic auth headers this function would be called once for each header until first valid result is returned Required. | L28 |
Realm | string | Realm is a string to define realm attribute of BasicAuthWithConfig. Default value "Restricted". | L32 |
AllowedCheckLimit | uint | AllowedCheckLimit set how many headers are allowed to be checked. This is useful environments like corporate test environments with application proxies restricting access to environment with their own auth scheme. Defaults to 1. | L38 |
Validator 的签名为:
type BasicAuthValidator func(c *echo.Context, user string, password string) (bool, error)// Effective defaults applied when fields are left unset.BasicAuthConfig{ Skipper: DefaultSkipper, Realm: "Restricted",}