Spring Cloud Gateway: Route and Mutate Request Headers

Conceal and Leverage Security Related Headers From Within.

Dev INTJ Code
Javarevisited
3 min readJul 26, 2022

--

Photo by Sugarman Joe on Unsplash

Introduction

These days, it’s not unusual to see applications using token-based authorization; however, while there’s generally nothing wrong with it — it’s almost always good to limit the exposure of these tokens as much as possible.

In that case, why don’t we check out Spring Cloud Gateway? Let’s leverage its routing mechanism and handle the mutation of request headers from within.

So, without further ado — let’s get a simple gateway service up and running.

Project Setup

First, let’s suppose we have an internal API that hypothetically needs a header that must be kept secured and private — that might be an API key, client credentials, and whatnot. While it would be fun to implement any of that, in this article — we won’t be diving into those details; Instead, we’ll have a hypothetical API to focus solely on Spring Cloud Gateway.

So now, let’s have a look at the necessary dependencies in our pom.xml:

This pom.xml is almost self-explanatory; however, I’d like to point out the netty-resolver-dns-native-macos dependency — which we can use to solve netty compatibility errors in an M1 chip.

Next, through an application.yml file — let’s configure routing for a hypothetical service:

From the snippet above, we can tell that requests with a prefix of /hypothetical-path (under predicates) will get routed directly to the URI. Also, notice that we use StripPrefix under filters — which enables the routing of the request to our hypothetical service without the trailing prefix.

Lastly, let’s implement a custom GlobalFilter to include a header into the request before the request routing happens:

Up and Running

We’re almost there — so first, let’s make sure we have a running service to route the request from the gateway service. In our case, we can use our hypothetical-api.

Now, all that’s left is to run and try sending a request through the gateway service:

curl -v http://localhost:8081/hypothetical-path

If we are to check the logs, we can see that we’ve successfully routed and added a header to the request:

So, there we have it. With Spring Cloud Gateway, we had been able to route and mutate the request with minimal configuration and a single filter.

As usual, the entire source code is always available on GitHub.

--

--

Dev INTJ Code
Javarevisited

Senior Software Engineer specializing in Backend Development, particularly in Java, utilizing the tech within the Spring Framework ecosystem;