fix: accept bare admin JWT authorization header

Allow the admin JWT middleware to parse either Authorization: Bearer <jwt>
or a bare JWT value, matching the existing comment. Add tests covering both
accepted forms plus missing and empty authorization headers.
This commit is contained in:
line-6000
2026-05-22 15:03:59 +08:00
parent c19a7e5f2c
commit f4ef71b359
2 changed files with 141 additions and 10 deletions
+23 -10
View File
@@ -27,16 +27,9 @@ const (
func CheckAdminJWT() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
raw := strings.TrimSpace(ctx.Request().Header.Get("Authorization"))
if raw == "" {
return echo.NewHTTPError(http.StatusUnauthorized, "missing authorization header")
}
if !strings.HasPrefix(raw, "Bearer ") {
return echo.NewHTTPError(http.StatusUnauthorized, "authorization header must use Bearer scheme")
}
token := strings.TrimSpace(raw[len("Bearer "):])
if token == "" {
return echo.NewHTTPError(http.StatusUnauthorized, "empty token")
token, err := adminTokenFromAuthorization(ctx.Request().Header.Get("Authorization"))
if err != nil {
return err
}
claims, err := appjwt.Parse(token)
if err != nil {
@@ -48,3 +41,23 @@ func CheckAdminJWT() echo.MiddlewareFunc {
}
}
}
func adminTokenFromAuthorization(header string) (string, error) {
raw := strings.TrimSpace(header)
if raw == "" {
return "", echo.NewHTTPError(http.StatusUnauthorized, "missing authorization header")
}
const bearerPrefix = "Bearer "
token := raw
if strings.HasPrefix(raw, bearerPrefix) {
token = strings.TrimSpace(raw[len(bearerPrefix):])
} else if raw == strings.TrimSpace(bearerPrefix) {
token = ""
}
if token == "" {
return "", echo.NewHTTPError(http.StatusUnauthorized, "empty token")
}
return token, nil
}