Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Building API Gateways with Spring Cloud Gateway, Nacos, and Custom Filters

Tech Sep 4 1

Dependencies

Add the following starters to your pom.xml (or equivalent Gradle coordiantes):

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

These modules enable service registration with Nacos and reactive gateway capabilities.

Service & Route Configuration

Below is a minimal application.yml that registers the gateway in Nacos and defines two load‑balanced routes:

server:
  port: 10010

spring:
  application:
    name: gateway-service
  cloud:
    nacos:
      server-addr: localhost:8848
      discovery:
        namespace: 16035e26-9a58-403c-9308-083325c0f8ee
    gateway:
      routes:
        - id: users-route
          uri: lb://userservice
          predicates:
            - Path=/user/**
        - id: orders-route
          uri: lb://orderservice
          predicates:
            - Path=/order/**
  • uri: lb://<service-name> enables client‑side load balancing through the service registry.
  • Static URIs such as http://127.0.0.1:8081 are also supported.
  • Predicate names (e.g., Path) are case‑sensitive.

Official route predicate factories are documented in the Spring Cloud Gateway reference.

Route‑Specific and Default Filters

GatewayFilter instances operate on both incoming requests and outgoing responses. You can attach them to individual routes or apply them globally.

spring:
  cloud:
    gateway:
      routes:
        - id: orders-route
          uri: lb://orderservice
          predicates:
            - Path=/order/**
          filters:
            - AddRequestHeader=X-Request-Source, ordermanagement
      default-filters:
        - AddRequestHeader=X-Request-Source, gateway-global
  • Filters listed under a specific route only affect that route.
  • default-filters are applied to every route defined in the gateway.

Custom Global Filter

Implement GlobalFilter to define logic that runs for every request. The example below checks for a query parameter named access_token:

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
public class TokenValidationFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest()
                .getQueryParams()
                .getFirst("access_token");

        if ("secret-2025".equals(token)) {
            return chain.filter(exchange);
        }

        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}

avian orders define the filter chain priority. Lower numeric values mean earlier execution.

Filter Execution Order

  • Priority is determined by @Order or the Ordered interface; smaller values run first.
  • When two filters share the same order, the sequence is: default filtersroute‑specific filtersglobal filters.

Cross‑Origin (CORS) Configuration

Gateways often need to handle browser cross‑domain requests. Enable global CORS settings in application.yml:

spring:
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        cors-configurations:
          '[/**]':
            allowedOrigins:
              - "http://client-app:8090"
              - "http://www.example-shop.com"
            allowedMethods:
              - GET
              - POST
              - PUT
              - DELETE
              - OPTIONS
            allowedHeaders: "*"
            allowCredentials: true
            maxAge: 360000
  • Setting add-to-simple-url-handler-mapping prevents OPTIONS preflight requests from being blocked. -itable origins, methods, headers, and cookie handling can be tuned per path pattern.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.