Spaces:
Sleeping
Sleeping
File size: 869 Bytes
c5eab62 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package middleware
import (
"log"
"monica-proxy/internal/config"
"net/http"
"strings"
"github.com/labstack/echo/v4"
)
// BearerAuth 创建一个Bearer Token认证中间件
func BearerAuth() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// 获取Authorization header
auth := c.Request().Header.Get("Authorization")
// 检查header格式
if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
return echo.NewHTTPError(http.StatusUnauthorized, "invalid authorization header")
}
// 提取token
token := strings.TrimPrefix(auth, "Bearer ")
// 验证token
if token != config.MonicaConfig.BearerToken || token == "" {
log.Printf("invalid token: %s", token)
return echo.NewHTTPError(http.StatusUnauthorized, "invalid token")
}
return next(c)
}
}
}
|