BearerTokenMiddleware validates bearer token authentication
(expectedToken string)
| 897 | |
| 898 | // BearerTokenMiddleware validates bearer token authentication |
| 899 | func BearerTokenMiddleware(expectedToken string) echo.MiddlewareFunc { |
| 900 | return func(next echo.HandlerFunc) echo.HandlerFunc { |
| 901 | return func(c echo.Context) error { |
| 902 | // Skip authentication for health and readiness endpoints |
| 903 | if c.Path() == "/health" || c.Path() == "/ready" { |
| 904 | return next(c) |
| 905 | } |
| 906 | |
| 907 | auth := c.Request().Header.Get("Authorization") |
| 908 | if auth == "" { |
| 909 | return echo.NewHTTPError(http.StatusUnauthorized, "missing Authorization header") |
| 910 | } |
| 911 | |
| 912 | // Extract Bearer token |
| 913 | const prefix = "Bearer " |
| 914 | if len(auth) < len(prefix) || auth[:len(prefix)] != prefix { |
| 915 | return echo.NewHTTPError(http.StatusUnauthorized, "invalid Authorization header format") |
| 916 | } |
| 917 | |
| 918 | token := auth[len(prefix):] |
| 919 | if subtle.ConstantTimeCompare([]byte(token), []byte(expectedToken)) != 1 { |
| 920 | return echo.NewHTTPError(http.StatusUnauthorized, "invalid token") |
| 921 | } |
| 922 | |
| 923 | return next(c) |
| 924 | } |
| 925 | } |
| 926 | } |