必须在路由注册前配置BasicAuth中间件,否则请求绕过认证;支持路由组局部启用、自定义Validator动态校验(含数据库查用户)、全局启用并排除/health等路径。

要在Fiber框架中为API接口快速启用BasicAuth基础认证,避免未授权访问暴露敏感数据,必须在路由注册前完成中间件配置,否则所有请求将绕过认证直接到达处理器。
添加BasicAuth中间件到指定路由
打开main.go文件,在定义路由组的位置插入fiber.BasicAuth()中间件。例如,对/admin路径下所有接口统一加锁:
app.Group("/admin").Use(fiber.BasicAuth{Username: "admin", Password: "123456"})
这行代码会拦截所有以/admin开头的请求,并强制校验Authorization头中的Base64编码凭据。注意:用户名和密码是明文写死的,【生产环境严禁硬编码】,应从环境变量或配置中心读取。
自定义认证逻辑(支持数据库/Redis查用户)
方法一:使用fiber.BasicAuthFunc实现动态校验
创建一个函数,接收username和password两个字符串参数,返回true表示通过,false拒绝:
auth := fiber.BasicAuth{Validator: func(c *fiber.Ctx, username, password string) bool { return username == "api" && password == "token2026" }}
方法二:接入外部服务做校验
在Validator函数内调用数据库查询或调用Auth Service的HTTP接口,比如用sqlx查users表匹配加密后的密码哈希值。此时务必确保密码比对使用bcrypt.CompareHashAndPassword,绝不能用==直接比较明文密码。
全局启用BasicAuth并排除健康检查路径
第一步:在app.Use()中注册BasicAuth中间件,覆盖全部路由
第二步:在中间件后立即注册一个匿名路由,显式放行/health路径
app.Use(fiber.BasicAuth{Username: "monitor", Password: "ping123"}) → app.Get("/health", func(c *fiber.Ctx) error { return c.SendString("OK") })
第三步:确保该/health路由声明在BasicAuth中间件之后、其他业务路由之前,否则仍会被拦截
第四步:启动服务后,用curl -u monitor:ping123 http://localhost:3000/health测试是否成功绕过认证


















