Auth and Rate Limiting Middleware
JWT validation and token bucket rate limiting
JWT auth middleware
Extract, parse, and validate a JWT from the Authorization header:
func JWTAuth(secret []byte) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
http.Error(w, "missing token", 401); return
}
token := strings.TrimPrefix(header, "Bearer ")
claims, err := parseJWT(token, secret)
if err != nil {
http.Error(w, "invalid token", 401); return
}
ctx := context.WithValue(r.Context(), claimsKey{}, claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}API key auth
Validate an API key from a header against a database or in-memory set:
func APIKeyAuth(validKeys map[string]bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("X-API-Key")
if !validKeys[key] {
http.Error(w, "forbidden", 403); return
}
next.ServeHTTP(w, r)
})
}
}All lessons in this course
- HTTP Middleware Chain Fundamentals
- Logging and Request ID Middleware
- Auth and Rate Limiting Middleware
- CORS and Panic Recovery Middleware