Skip to content

d. Authorization

The gateway-service is the single entry point for all requests. Beyond routing, it enforces authentication: before forwarding any request to a secured service, it checks for a valid JWT cookie and resolves the caller's identity. This is done through two components β€” RouterValidator and AuthorizationFilter.

1. How Authorization Works

The Gateway uses Spring Cloud Gateway's GlobalFilter mechanism. Every request passes through AuthorizationFilter before being routed. The filter follows this decision tree:

flowchart TD
    A[Incoming request] --> B{RouterValidator\nisSecured?}
    B -- No --> C[Forward to service]
    B -- Yes --> D{Cookie\n__store_jwt_token\npresent?}
    D -- No --> E[401 Unauthorized]
    D -- Yes --> F[POST /auth/solve\nwith JWT]
    F --> G{Valid token?}
    G -- No --> E
    G -- Yes --> H[Add id-account header]
    H --> C

When the token is valid, the filter enriches the downstream request with one header:

Header Value Purpose
id-account Account UUID from token (jti) Services use this to identify the caller

Before that, the Gateway removes any id-account sent by the client (RemoveRequestHeader=id-account in default-filters, which run before AuthorizationFilter): otherwise anyone could call a secured route pretending to be another account. The header that reaches the services can only come from the Gateway.

sequenceDiagram
    actor C as Client
    participant G as Gateway
    participant A as auth
    participant S as account
    C->>G: GET /accounts with the cookie of Antonio and id-account of another user
    G->>G: RemoveRequestHeader=id-account
    G->>A: POST /auth/solve (token)
    A-->>G: idAccount of Antonio
    G->>S: GET /accounts with id-account of Antonio
    Note over C,S: the id-account that reaches a service comes only from the token

This means downstream microservices never need to parse JWTs themselves β€” the Gateway handles it and passes the resolved identity as a plain header.

2. Full Request Sequence

sequenceDiagram
  autonumber
  actor User
  User->>+Gateway: request with cookie __store_jwt_token
  Gateway->>+AuthorizationFilter: filter(exchange, chain)
  AuthorizationFilter->>RouterValidator: isSecured.test(request)
  RouterValidator-->>AuthorizationFilter: true
  AuthorizationFilter->>AuthorizationFilter: read cookie value
  AuthorizationFilter->>+Auth Service: POST /auth/solve (token)
  Auth Service->>Auth Service: JwtService.getId(token)
  Auth Service-->>-AuthorizationFilter: { idAccount: "..." }
  AuthorizationFilter->>AuthorizationFilter: mutate request headers
  AuthorizationFilter->>-Gateway: chain.filter(mutated exchange)
  Gateway->>-User: service response

3. The gateway-service Module

3.1 Repository

Create a new git repository for the gateway service and add it as a submodule:

git submodule add <repository_url> api/gateway-service
πŸ“ api/
β”œβ”€β”€ πŸ“ account/
β”œβ”€β”€ πŸ“ account-service/
β”œβ”€β”€ πŸ“ auth/
β”œβ”€β”€ πŸ“ auth-service/
└── πŸ“ gateway-service/

3.2 Code

Use Spring Initializr to generate a Maven project with the following settings:

  • Group: store
  • Artifact: gateway-service
  • Package name: store.gateway
  • Packaging: Jar
  • Java: 25

Dependencies to add:

  • Gateway (spring-cloud-starter-gateway-server-webflux) β€” reactive gateway with routing and filter support
  • Reactive Web (spring-boot-starter-webflux) β€” reactive stack required by Spring Cloud Gateway
  • WebClient (spring-boot-starter-webclient) β€” the shared WebClient.Builder the filter uses to call auth (Spring Boot 4 moved it out of WebFlux)

Reactive stack

Spring Cloud Gateway runs on Project Reactor (WebFlux), not on the traditional servlet stack. This is why AuthorizationFilter returns Mono<Void> instead of void, and why the HTTP client inside it uses WebClient instead of RestTemplate.

The resulting structure is:

πŸ“ api/
└── πŸ“ gateway-service/
    β”œβ”€β”€ πŸ“ src/
    β”‚   └── πŸ“ main/
    β”‚       β”œβ”€β”€ πŸ“ java/
    β”‚       β”‚   └── πŸ“ store/
    β”‚       β”‚       └── πŸ“ gateway/
    β”‚       β”‚           β”œβ”€β”€  GatewayServiceApplication.java
    β”‚       β”‚           β”œβ”€β”€  GatewayResource.java
    β”‚       β”‚           └── πŸ“ security/
    β”‚       β”‚               β”œβ”€β”€  AuthorizationFilter.java
    β”‚       β”‚               └──  RouterValidator.java
    β”‚       └── πŸ“ resources/
    β”‚           └── YAML application.yaml
    β”œβ”€β”€  pom.xml
    └── Docker Dockerfile
Class Description
GatewayServiceApplication Spring Boot entry point
GatewayResource The Gateway's own GET /health-check; answers with the container's HOSTNAME, handy to see which replica answered
RouterValidator Holds the list of open routes; provides an isSecured predicate
AuthorizationFilter Global filter; validates the JWT cookie and enriches the request

3.3 RouterValidator in detail

RouterValidator defines which routes bypass authentication. It stores them as "METHOD /path" strings and exposes an isSecured predicate. A request matches an open route if the HTTP method and path both match (with optional /** wildcard support).

private List<String> openApiEndpoints = List.of(
    "POST /auth/register",
    "GET /auth/logout",
    "POST /auth/login"
);

Any request not matching this list returns true from isSecured, meaning the filter will require a valid cookie.

3.4 Application configuration

The application.yaml defines the CORS policy, the default filters and the route table. Routes map URL patterns to upstream service hostnames (resolved inside the Docker Compose network):

default-filters:
  - RemoveRequestHeader=id-account
  - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

routes:
  - id: account-service
    uri: http://account:8080
    predicates:
      - Path=/accounts/**

  - id: auth-service
    uri: http://auth:8080
    predicates:
      - Path=/auth/**

Source

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>store</groupId>
    <artifactId>gateway-service</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>25</java.version>
        <spring-cloud.version>2025.1.3</spring-cloud.version>
        <maven.compiler.proc>full</maven.compiler.proc>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webclient</artifactId>
        </dependency>

    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
spring:
  application:
    name: gateway

  cloud:
    gateway:
      server:
        webflux:

          default-filters:
            - RemoveRequestHeader=id-account
            - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

          globalcors:
            corsConfigurations:
              '[/**]':
                allowedOrigins: ${CORS_ALLOWED_ORIGINS:http://localhost,http://localhost:3000,http://localhost:8080}
                allowedHeaders: "*"
                allowedMethods: "*"
                allowCredentials: true

          routes:

            - id: insper-service
              uri: https://www.insper.edu.br
              predicates:
                - Path=/insper/**

            - id: account-service
              uri: http://account:8080
              predicates:
                - Path=/accounts/**

            - id: auth-service
              uri: http://auth:8080
              predicates:
                - Path=/auth/**

logging:
  level:
    root: info
    store: debug
    org.springframework.web: debug
package store.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GatewayServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayServiceApplication.class, args);
    }

}
package store.gateway;

import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GatewayResource {

    @GetMapping("/health-check")
    public ResponseEntity<Map<String, String>> healthCheck() {
        // only the container's hostname: it tells which replica answered
        // (never return System.getenv(): it would expose every secret)
        return ResponseEntity.ok(Map.of(
            "hostname", System.getenv().getOrDefault("HOSTNAME", "unknown")
        ));
    }

}
package store.gateway.security;

import java.util.List;
import java.util.function.Predicate;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

@Component
public class RouterValidator {

    private List<String> openApiEndpoints = List.of(
            "POST /auth/register",
            "GET /auth/logout",
            "POST /auth/login");

    public Predicate<ServerHttpRequest> isSecured = request -> openApiEndpoints
            .stream()
            .noneMatch(uri -> {
                String[] parts = uri.replaceAll("[^a-zA-Z0-9// *]", "").split(" ");
                final String method = parts[0];
                final String path = parts[1];
                final boolean deep = path.endsWith("/**");
                return ("ANY".equalsIgnoreCase(method) || request.getMethod().toString().equalsIgnoreCase(method))
                        && (request.getURI().getPath().equals(path)
                                || (deep && request.getURI().getPath().startsWith(path.replace("/**", ""))));
            });

}
package store.gateway.security;

import java.time.Duration;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

@Component
public class AuthorizationFilter implements GlobalFilter {

    private static final Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);

    public static final String AUTH_COOKIE_TOKEN = "__store_jwt_token";
    public static final String AUTH_SERVICE_URL = "http://auth:8080";
    public static final String AUTH_SERVICE_TOKEN_SOLVE = "/auth/solve";
    private static final Duration AUTH_TIMEOUT = Duration.ofSeconds(3);

    private final RouterValidator routerValidator;

    // built once and reused by every request: the client is thread-safe
    private final WebClient authClient;

    public AuthorizationFilter(RouterValidator routerValidator, WebClient.Builder builder) {
        this.routerValidator = routerValidator;
        this.authClient = builder
            .baseUrl(AUTH_SERVICE_URL)
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .build();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // get the request content
        final ServerHttpRequest request = exchange.getRequest();

        // check if the route is open
        if (!routerValidator.isSecured.test(request)) {
            logger.debug("this route is open");
            return chain.filter(exchange);
        }

        // route is not open: the cookie with the jwt is required
        final HttpCookie cookie = request.getCookies().getFirst(AUTH_COOKIE_TOKEN);
        if (cookie == null || cookie.getValue().isBlank()) {
            return Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED));
        }

        logger.debug("I got the cookie");
        return requestAuthTokenSolve(exchange, chain, cookie.getValue().trim());
    }

    private Mono<Void> requestAuthTokenSolve(
        ServerWebExchange exchange,
        GatewayFilterChain chain,
        final String jwt) {

        return authClient.post()
            .uri(AUTH_SERVICE_TOKEN_SOLVE)
            .bodyValue(Map.of("token", jwt))
            .retrieve()
            // an invalid or expired token is a 401, not a 500
            .onStatus(HttpStatusCode::is4xxClientError,
                response -> Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid token")))
            .bodyToMono(new ParameterizedTypeReference<Map<String, String>>() {})
            // a hung auth service must not hold requests in the gateway forever
            .timeout(AUTH_TIMEOUT)
            .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid token")))
            .flatMap(map -> {
                logger.debug(map.toString());
                return chain.filter(updateRequest(exchange, map.get("idAccount")));
            });
    }

    private ServerWebExchange updateRequest(ServerWebExchange exchange, String idAccount) {
        return exchange.mutate()
            .request(
                exchange.getRequest()
                    .mutate()
                    .header("id-account", idAccount)
                    .build()
            ).build();
    }

}
1
2
3
4
FROM eclipse-temurin:25
VOLUME /tmp
COPY target/*.jar /app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

Health check: expose only what you need

/health-check is the Gateway's own endpoint, not a route, so AuthorizationFilter does not run on it β€” anyone can call it. Answer only what it needs (here, the hostname); returning System.getenv() would expose every environment variable, secrets included.

Invalid token β†’ 401

retrieve() turns an error answer from /auth/solve into an exception, and an unhandled exception in the Gateway is a 500. The onStatus(...) maps the 401 of an invalid or expired token to a 401 at the Gateway, so the front end knows it must log in again. It only works if auth answers 401 itself: /auth/solve catches the JwtException of a malformed, edited or expired token (open routes); an uncaught one is a 500 that passes through the Gateway as a 500.

One WebClient, built once

The filter builds its WebClient once, in the constructor, from the WebClient.Builder that Spring injects, and reuses it on every request: the client is thread-safe. Calling WebClient.builder()...build() inside filter() works, but repeats the setup (codecs, connector) on every secured request. The injected builder also adds metrics (http_client_requests with client_name="auth") and tracing, and the timeout(...) keeps a hung auth from holding requests in the Gateway.

A client per request is waste, not a memory leak. We measured it: 4 rounds, about 510 thousand requests, a full garbage collection (GC) after each round, and the live heap stayed at 22–24 MiB. What grows and does not come back is the heap the Java Virtual Machine (JVM) reserves (here, up to 316 MiB): without -Xmx or a memory limit, the JVM takes up to 25% of the host memory and gives it back only after a full GC. To tell one from the other, look at the heap after a GC (jcmd 1 GC.run, then jcmd 1 GC.heap_info), not at docker stats.

4. Updating Docker Compose

Add the auth service to the compose.yaml of Hands-on 2. Like account, it publishes no port: only the Gateway is reachable from outside, while account and auth are reached only inside the Compose network, by their service names β€” the trusted layer.

name: store

services:

  db:
    image: postgres:17
    volumes:
      - ${VOLUME_DB}:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: ${DB_USER:-store}
      POSTGRES_PASSWORD: ${DB_PASSWORD:-store}
      POSTGRES_DB: ${DB_NAME:-store}

  account:
    build:
      context: ./account-service
      dockerfile: Dockerfile
    environment:
      DATABASE_HOST: db
      DATABASE_PORT: 5432
      DATABASE_DB: ${DB_NAME:-store}
      DATABASE_USERNAME: ${DB_USER:-store}
      DATABASE_PASSWORD: ${DB_PASSWORD:-store}
    deploy:
      replicas: 1
    depends_on:
      - db

  auth:
    build:
      context: ./auth-service
      dockerfile: Dockerfile

  gateway:
    build:
      context: ./gateway-service
      dockerfile: Dockerfile
    ports:
      - 8080:8080
    deploy:
      replicas: 1
flowchart LR
    host["your machine\ncurl, browser"]
    subgraph net [Compose network: the trusted layer]
        gateway["gateway\n8080:8080"]
        auth["auth\n:8080"]
        account["account\n:8080"]
        db[("db\n:5432")]
    end
    host e0@==>|"localhost:8080"| gateway
    gateway e1@--> auth
    gateway e2@--> account
    auth --> account
    account --> db
    e0@{ animate: true }

auth and gateway need no variables to run on your machine: auth's application.yaml reads JWT_SECRET_KEY, JWT_HTTP_ONLY and JWT_DURATION with development defaults, and the Gateway reads CORS_ALLOWED_ORIGINS (default http://localhost,http://localhost:3000,http://localhost:8080).

JWT_SECRET_KEY outside development

The default key in application.yaml is public β€” it is in the repository β€” so anyone could forge tokens for a deployment that keeps it. Generate a key of your own, with 256 bits (32 random bytes, Base64-encoded):

openssl rand -base64 32

and hand it to auth from the environment β€” e.g. in compose.yaml, with the value in a .env file that is never committed:

  auth:
    environment:
      JWT_SECRET_KEY: ${JWT_SECRET_KEY}

5. Testing the Security Layer

Start the platform:

docker compose up -d --build

Register a new user:

curl -X POST http://localhost:8080/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name": "Antonio do Estudo", "email": "acme@insper.edu.br", "password": "123@321"}'

Login and capture the cookie:

curl -c cookies.txt -X POST http://localhost:8080/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "acme@insper.edu.br", "password": "123@321"}'

Access a secured endpoint using the cookie:

curl -b cookies.txt http://localhost:8080/accounts

Access without the cookie β€” expect 401:

curl http://localhost:8080/accounts

What each case should answer:

Request Cookie Expected
POST /auth/register none (open route) βœ… 200
POST /auth/login none (open route) βœ… 200 + Set-Cookie: __store_jwt_token=…
POST /auth/login, wrong password none ❌ 401, not 500
GET /accounts valid βœ… 200 + the accounts
GET /accounts none ❌ 401
GET /accounts expired, edited or signed with another key ❌ 401, not 500

Try it

No Docker at hand, or want to see what each request does inside? The simulator runs the lab's stack: every button is a curl through the Gateway, and the boxes light up along the path the request took. In Authorization 5 (test), the four commands of the page answer 200, 200, 200 and 401, and the login issues exactly the example token of the JWT page: valid until 14:00:00, 3600 s after its nbf. In bad tokens, a wrong password is a 401, a forged id-account header is dropped, an edited payload fails the signature, and a token signed again with the public default key gets 200 as Ana β€” until JWT_SECRET_KEY is your own. Past the cookie's Max-Age, curl stops sending it; sent by hand, the token meets ExpiredJwtException.


Done! The security layer is complete. Every request to a secured route now passes through the Gateway, which validates the JWT cookie with auth-service and forwards the resolved identity to downstream services β€” without any service needing to parse tokens themselves.