Chapter 04 of 8
How the Gateway transforms and authenticates incoming requests through the middleware chain.
Middleware in OpenFaaS Gateway is software that sits between the incoming HTTP request and the final handler, processing requests in a chain-like fashion to add functionality like authentication, logging, and request transformation.
The middleware pipeline processes requests in a specific sequence, with each middleware component having the opportunity to inspect, modify, or reject the request.
HTTP request reaches the Gateway
Handles cross-origin requests
Validates API keys or tokens
Checks request frequency limits
Records request details
Request reaches the final handler
The authentication middleware is responsible for validating the identity of clients making requests to the OpenFaaS Gateway.
Validates API keys from request headers or query parameters. Supports multiple key formats and validation strategies.
Validates JSON Web Tokens for more sophisticated authentication scenarios with expiration and claims validation.
Supports HTTP Basic Authentication for simple username/password scenarios.
Integrates with OAuth providers for enterprise authentication scenarios.
Middleware can transform incoming requests to add additional context, modify headers, or prepare the request for processing.
Adds request ID, timestamp, or user context
Adds metadata from authentication or logging
Transforms request body or query parameters
Injects request context for downstream handlers
Here's how middleware is implemented in the OpenFaaS Gateway codebase.
func setupMiddleware(router *mux.Router) { // CORS middleware router.Use(middleware.CORS()) // Authentication middleware router.Use(middleware.Auth()) // Rate limiting router.Use(middleware.RateLimit()) // Request logging router.Use(middleware.Logging())}func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Validate API key if !validateAPIKey(r) { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // Continue to next handler next.ServeHTTP(w, r) })}
The middleware layer provides essential security features to protect the OpenFaaS Gateway from various types of attacks and abuse.
Prevents abuse by limiting the number of requests from a single client within a time window.
Validates and sanitizes input to prevent injection attacks and malformed requests.
Controls which domains can access the API to prevent unauthorized cross-origin requests.
Logs all requests for security auditing and monitoring suspicious activity.
Now that you understand how requests are processed through middleware, let's explore how functions are invoked synchronously and asynchronously.