Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you implement JWT authentication middleware in Go?
JWT (JSON Web Token) authentication middleware validates the token on every request, extracts claims, and attaches them to the request context for use by downstream handlers.
import "github.com/golang-jwt/jwt/v5" type Claims struct { UserID int `json:"user_id"` Role string `json:"role"` jwt.RegisteredClaims } type contextKey string const claimsKey contextKey = "claims" func jwtMiddleware(secret []byte) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Extract token from Authorization: Bearer auth := r.Header.Get("Authorization") if !strings.HasPrefix(auth, "Bearer ") { writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "missing bearer token"}) return } tokenString := strings.TrimPrefix(auth, "Bearer ") // Parse and validate var claims Claims token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (any, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return secret, nil }) if err != nil || !token.Valid { writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid or expired token"}) return } // Attach claims to context ctx := context.WithValue(r.Context(), claimsKey, &claims) next.ServeHTTP(w, r.WithContext(ctx)) }) } } // Helper to extract claims in handlers func claimsFromCtx(ctx context.Context) (*Claims, bool) { c, ok := ctx.Value(claimsKey).(*Claims) return c, ok }
More Related questions...