跳到主要内容
版本: v2.x

BasicAuth

用于 Fiber 的 Basic Authentication 中间件,提供 HTTP Basic Authentication 功能。它会对有效的凭据调用下一个处理器,对于缺失或无效的凭据则返回 401 未授权 或自定义响应。

签名

func New(config Config) fiber.Handler

示例

导入 Fiber Web 框架的中间件包

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/basicauth"
)

初始化 Fiber 应用后,可以使用以下方式

// Provide a minimal config
app.Use(basicauth.New(basicauth.Config{
Users: map[string]string{
"john": "doe",
"admin": "123456",
},
}))

// Or extend your config for customization
app.Use(basicauth.New(basicauth.Config{
Users: map[string]string{
"john": "doe",
"admin": "123456",
},
Realm: "Forbidden",
Authorizer: func(user, pass string) bool {
if user == "john" && pass == "doe" {
return true
}
if user == "admin" && pass == "123456" {
return true
}
return false
},
Unauthorized: func(c *fiber.Ctx) error {
return c.SendFile("./unauthorized.html")
},
ContextUsername: "_user",
ContextPassword: "_pass",
}))

配置

属性类型描述默认值
下一个func(*fiber.Ctx) boolNext 定义了一个函数,当返回 true 时跳过此中间件。nil
Usersmap[string]stringUsers 定义了允许的凭据。map[string]string{}
RealmstringRealm 是一个字符串,用于定义 BasicAuth 的 realm 属性。realm 用于标识需要认证的系统,客户端可以使用它来保存凭据。"Restricted"
Authorizerfunc(string, string) boolAuthorizer 定义了一个函数来检查凭据。它会传入用户名和密码,并期望返回 true 或 false 表示批准。nil
Unauthorizedfiber.HandlerUnauthorized 定义了未经授权响应的响应体。nil
ContextUsernameinterface{}ContextUsername 是在 Locals 中存储用户名的键。"username"
ContextPasswordinterface{}ContextPassword 是在 Locals 中存储密码的键。"password"

默认配置

var ConfigDefault = Config{
Next: nil,
Users: map[string]string{},
Realm: "Restricted",
Authorizer: nil,
Unauthorized: nil,
ContextUsername: "username",
ContextPassword: "password",
}