Understanding and Implementing API Gateway with Spring Cloud Gateway

This article explains the role of an API gateway in microservice architectures, details why Spring Cloud Gateway is chosen, describes its workflow, predicates, filters, dynamic routing, and demonstrates token authentication with code examples, helping developers integrate a unified entry point for their services.

Wukong Talks Architecture
Wukong Talks Architecture
Wukong Talks Architecture
Understanding and Implementing API Gateway with Spring Cloud Gateway

In the PassJava project, Spring Cloud Gateway is used as the API gateway, routing all client requests through the gateway before forwarding them to member, question, and other microservices, allowing clients to hide internal service addresses.

Compared to a monolithic SpringBoot architecture, microservice architectures involve multiple services possibly deployed on different machines, leading to challenges such as adding authentication, traffic control, CORS handling, security exposure, and gray releases for each service. An API gateway provides a single entry point to address these issues.

The article outlines common gateway options (Spring Cloud Gateway, Netflix Zuul, Nginx, Kong, Alibaba Tengine) and selects Spring Cloud Gateway as the preferred component.

Spring Cloud Gateway workflow:

1. Route Predicate : The request passes through Gateway Handler Mapping to evaluate predicates and match a route.

2. Request Filters (Pre-Filters) : A filter chain can modify the request (e.g., add headers, validate parameters) before forwarding to the backend service.

3. Service Processing : The backend service handles the request.

4. Response Filters (Post-Filters) : After the service returns, response filters can modify the response.

5. Response Return : The final response is sent back to the client.

The gateway uses Predicate configurations to match routes. Example predicate configuration (YAML):

spring:
  cloud:
    gateway:
      routes:
        - id: route_qq
          uri: http://www.qq.com
          predicates:
            - Query=url,qq
        - id: route_baidu
          uri: http://www.baidu.com
          predicates:
            - Query=url,baidu
server:
  port: 8060

Dynamic routing is achieved by using service names (e.g., lb://passjava-question) and letting the gateway discover instances via a registration center, supporting load balancing without manual configuration changes.

Filters are categorized as Pre and Post, as well as GlobalFilter (applied to all routes) and GatewayFilter (applied to specific routes). The article lists 27 built‑in filters and shows an example of a rewrite filter:

filters:
  - RewritePath=/api/(?<segment>.*),/${segment}

A custom global filter for token authentication is demonstrated. The filter checks the token header; if the token equals "admin", the request proceeds, otherwise a 401 Unauthorized response is returned.

@Component
public class GlobalLoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.isEmpty(token)) {
            if ("admin".equals(token)) {
                return chain.filter(exchange);
            }
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
    @Override
    public int getOrder() { return 0; }
}

Testing shows a 401 response for an invalid token (e.g., token=123) and a successful response for a valid token ( token=admin).

The article concludes with a preview of the next tutorial on implementing JWT authentication with Spring Cloud Gateway.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaapi-gatewaySpringBootSpring Cloud
Wukong Talks Architecture
Written by

Wukong Talks Architecture

Explaining distributed systems and architecture through stories. Author of the "JVM Performance Tuning in Practice" column, open-source author of "Spring Cloud in Practice PassJava", and independently developed a PMP practice quiz mini-program.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.