2026-05-07 23:51:16 -06:00
|
|
|
package httpauthjwt
|
2026-05-07 22:18:04 -06:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
"path"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
|
|
|
|
|
|
|
|
httpauthmw "code.nochebuena.dev/go/httpauth"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// AuthMiddleware verifies the Bearer access token and injects uid + claims into
|
|
|
|
|
// the request context via httpauth.SetTokenData. Downstream middleware
|
|
|
|
|
// (EnrichmentMiddleware, AuthzMiddleware, ClaimsPermissionProvider) from
|
|
|
|
|
// code.nochebuena.dev/go/httpauth reads them transparently.
|
|
|
|
|
//
|
|
|
|
|
// Accepts a Verifier — pass a Signer or a NewRSAPublicKeyVerifier depending on
|
|
|
|
|
// whether the service issues tokens.
|
|
|
|
|
//
|
|
|
|
|
// Requests to publicPaths are skipped without token verification (wildcards
|
|
|
|
|
// supported via path.Match). Returns 401 on missing, invalid, or expired tokens.
|
|
|
|
|
func AuthMiddleware(verifier Verifier, publicPaths []string) func(http.Handler) http.Handler {
|
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
for _, pattern := range publicPaths {
|
|
|
|
|
if matched, _ := path.Match(pattern, r.URL.Path); matched {
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
authHeader := r.Header.Get("Authorization")
|
|
|
|
|
if !strings.HasPrefix(authHeader, "Bearer ") {
|
fix(httpauth-jwt): WithJSONNumber in Verify, JSON errors in AuthMiddleware, bump httpauth v1.0.2 (#1)
Pass jwt.WithJSONNumber() to jwt.Parse in hmacSigner.Verify, rsaSigner.Verify, and
rsaPublicVerifier.Verify. JWT numbers (including permission bitmasks) are now decoded
as json.Number instead of float64 — exact parsing for all integers including
math.MaxInt64 (the ADMIN wildcard mask). Float64 would round MaxInt64 to 2^63 and
overflow back to math.MinInt64 on cast to int64.
AuthMiddleware now calls httpauth.WriteJSONError for all 401 responses instead of
http.Error. Standardizes the error format across the full httpauth-* middleware stack:
AuthMiddleware (httpauth-jwt), EnrichmentMiddleware, and AuthzMiddleware (httpauth)
all produce {"code":"UNAUTHENTICATED"|"PERMISSION_DENIED"|"INTERNAL","message":"..."}.
Update two existing tests (TestIssueTokenPair_CustomClaims,
TestRefreshTokenPair_CustomClaimsInNewToken) to assert json.Number instead of float64
— they were correct before WithJSONNumber, now reflect the actual decoded type.
Add TestVerify_JSONNumberPreservesMaxInt64: issues a token with math.MaxInt64 as a
bitmask, verifies it, and asserts the decoded value is exactly math.MaxInt64 via
json.Number.Int64() — proving no float64 round-trip occurs.
Add TestAuthMiddleware_UnauthorizedJSON: asserts the 401 response is
Content-Type: application/json with body {"code":"UNAUTHENTICATED","message":"..."}.
Bump httpauth dependency to v1.0.2.
Reviewed-on: https://code.nochebuena.dev/go/httpauth-jwt/pulls/1
Co-authored-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
Co-committed-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
2026-05-18 14:38:54 -06:00
|
|
|
httpauthmw.WriteJSONError(w, http.StatusUnauthorized, "UNAUTHENTICATED", "unauthorized")
|
2026-05-07 22:18:04 -06:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
|
|
|
|
|
|
|
|
|
|
token, err := verifier.Verify(tokenStr)
|
|
|
|
|
if err != nil {
|
fix(httpauth-jwt): WithJSONNumber in Verify, JSON errors in AuthMiddleware, bump httpauth v1.0.2 (#1)
Pass jwt.WithJSONNumber() to jwt.Parse in hmacSigner.Verify, rsaSigner.Verify, and
rsaPublicVerifier.Verify. JWT numbers (including permission bitmasks) are now decoded
as json.Number instead of float64 — exact parsing for all integers including
math.MaxInt64 (the ADMIN wildcard mask). Float64 would round MaxInt64 to 2^63 and
overflow back to math.MinInt64 on cast to int64.
AuthMiddleware now calls httpauth.WriteJSONError for all 401 responses instead of
http.Error. Standardizes the error format across the full httpauth-* middleware stack:
AuthMiddleware (httpauth-jwt), EnrichmentMiddleware, and AuthzMiddleware (httpauth)
all produce {"code":"UNAUTHENTICATED"|"PERMISSION_DENIED"|"INTERNAL","message":"..."}.
Update two existing tests (TestIssueTokenPair_CustomClaims,
TestRefreshTokenPair_CustomClaimsInNewToken) to assert json.Number instead of float64
— they were correct before WithJSONNumber, now reflect the actual decoded type.
Add TestVerify_JSONNumberPreservesMaxInt64: issues a token with math.MaxInt64 as a
bitmask, verifies it, and asserts the decoded value is exactly math.MaxInt64 via
json.Number.Int64() — proving no float64 round-trip occurs.
Add TestAuthMiddleware_UnauthorizedJSON: asserts the 401 response is
Content-Type: application/json with body {"code":"UNAUTHENTICATED","message":"..."}.
Bump httpauth dependency to v1.0.2.
Reviewed-on: https://code.nochebuena.dev/go/httpauth-jwt/pulls/1
Co-authored-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
Co-committed-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
2026-05-18 14:38:54 -06:00
|
|
|
httpauthmw.WriteJSONError(w, http.StatusUnauthorized, "UNAUTHENTICATED", "unauthorized")
|
2026-05-07 22:18:04 -06:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
|
|
|
if !ok {
|
fix(httpauth-jwt): WithJSONNumber in Verify, JSON errors in AuthMiddleware, bump httpauth v1.0.2 (#1)
Pass jwt.WithJSONNumber() to jwt.Parse in hmacSigner.Verify, rsaSigner.Verify, and
rsaPublicVerifier.Verify. JWT numbers (including permission bitmasks) are now decoded
as json.Number instead of float64 — exact parsing for all integers including
math.MaxInt64 (the ADMIN wildcard mask). Float64 would round MaxInt64 to 2^63 and
overflow back to math.MinInt64 on cast to int64.
AuthMiddleware now calls httpauth.WriteJSONError for all 401 responses instead of
http.Error. Standardizes the error format across the full httpauth-* middleware stack:
AuthMiddleware (httpauth-jwt), EnrichmentMiddleware, and AuthzMiddleware (httpauth)
all produce {"code":"UNAUTHENTICATED"|"PERMISSION_DENIED"|"INTERNAL","message":"..."}.
Update two existing tests (TestIssueTokenPair_CustomClaims,
TestRefreshTokenPair_CustomClaimsInNewToken) to assert json.Number instead of float64
— they were correct before WithJSONNumber, now reflect the actual decoded type.
Add TestVerify_JSONNumberPreservesMaxInt64: issues a token with math.MaxInt64 as a
bitmask, verifies it, and asserts the decoded value is exactly math.MaxInt64 via
json.Number.Int64() — proving no float64 round-trip occurs.
Add TestAuthMiddleware_UnauthorizedJSON: asserts the 401 response is
Content-Type: application/json with body {"code":"UNAUTHENTICATED","message":"..."}.
Bump httpauth dependency to v1.0.2.
Reviewed-on: https://code.nochebuena.dev/go/httpauth-jwt/pulls/1
Co-authored-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
Co-committed-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
2026-05-18 14:38:54 -06:00
|
|
|
httpauthmw.WriteJSONError(w, http.StatusUnauthorized, "UNAUTHENTICATED", "unauthorized")
|
2026-05-07 22:18:04 -06:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
uid, _ := claims["sub"].(string)
|
|
|
|
|
if uid == "" {
|
fix(httpauth-jwt): WithJSONNumber in Verify, JSON errors in AuthMiddleware, bump httpauth v1.0.2 (#1)
Pass jwt.WithJSONNumber() to jwt.Parse in hmacSigner.Verify, rsaSigner.Verify, and
rsaPublicVerifier.Verify. JWT numbers (including permission bitmasks) are now decoded
as json.Number instead of float64 — exact parsing for all integers including
math.MaxInt64 (the ADMIN wildcard mask). Float64 would round MaxInt64 to 2^63 and
overflow back to math.MinInt64 on cast to int64.
AuthMiddleware now calls httpauth.WriteJSONError for all 401 responses instead of
http.Error. Standardizes the error format across the full httpauth-* middleware stack:
AuthMiddleware (httpauth-jwt), EnrichmentMiddleware, and AuthzMiddleware (httpauth)
all produce {"code":"UNAUTHENTICATED"|"PERMISSION_DENIED"|"INTERNAL","message":"..."}.
Update two existing tests (TestIssueTokenPair_CustomClaims,
TestRefreshTokenPair_CustomClaimsInNewToken) to assert json.Number instead of float64
— they were correct before WithJSONNumber, now reflect the actual decoded type.
Add TestVerify_JSONNumberPreservesMaxInt64: issues a token with math.MaxInt64 as a
bitmask, verifies it, and asserts the decoded value is exactly math.MaxInt64 via
json.Number.Int64() — proving no float64 round-trip occurs.
Add TestAuthMiddleware_UnauthorizedJSON: asserts the 401 response is
Content-Type: application/json with body {"code":"UNAUTHENTICATED","message":"..."}.
Bump httpauth dependency to v1.0.2.
Reviewed-on: https://code.nochebuena.dev/go/httpauth-jwt/pulls/1
Co-authored-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
Co-committed-by: Rene Nochebuena Guerrero <rene@nochebuena.dev>
2026-05-18 14:38:54 -06:00
|
|
|
httpauthmw.WriteJSONError(w, http.StatusUnauthorized, "UNAUTHENTICATED", "unauthorized")
|
2026-05-07 22:18:04 -06:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ctx := httpauthmw.SetTokenData(r.Context(), uid, map[string]any(claims))
|
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|