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