The Header Predicate in Spring Cloud API Gateway

One of the ways to make sure that an HTTP request to a web service endpoint contains an Authorization JWT token is to configure a gateway route to require an Authorization header.  This way, if the HTTP request does not contain an Authorization header, Spring Cloud API Gateway will not even route this request to a destination microservice.

We can achieve this by using the Header predicate. Let’s see how it works.

For a step by step series of video lessons, please check this page: Spring Boot Microservices and Spring Cloud.

Header Predicate

Let’s assume that a request to a /users/status/check web service endpoints requires a JWT token to be included in the Authorization HTTP Header.

To do that, I will add a Header predicate to a route configuration.[0].predicates[0]=Header=

The predicate is called Header. It is a built-in predicate that Spring Cloud API Gateway understands and knows what to do with it. The Header predicate accepts two values.

  1. The first value is the name of the header. Which is in our case is going to be “Authorization“. This is because, for this route to work, we want the HTTP request to contain the Authorization HTTP header.
  2. The second parameter is a header value which can be provided as a Java regular expression. For example, as a header value, I want it to be Bearer (.*).

So the header predicate will look like this now.[0].predicates[0]=Header=Authorization, Bearer (.*)

With this predicate added, Spring Cloud API Gateway will route HTTP requests sent to /users/status/check web service endpoint, only if this HTTP request contains an Authorization header with a value that matches Bearer (.*) regular expression. It will not validate the JWT token included in the Authorization header. It will just make sure that there is some Bearer token. To validate the included JWT toke we can create a filter and we can do it in the destination microservice as well.

Complete Route Configuration

Below is an example of a complete route configuration that uses the Header predicate.[0].id=users-status-check[0].uri = lb://users-ws[0].predicates[0]=Path=/users/status/check[0].predicates[1]=Method=GET[0].predicates[2]=Header=Authorization, Bearer (.*)[0].filters[0]=RemoveRequestHeader=Cookie

I hope this tutorial was of some value to you. If you are interested to learn more about building RESTful Web Services with Spring Boot and Spring Cloud and you enjoy learning by watching video lessons then check this page Spring Boot and Spring Cloud, please check this page: Spring Boot Microservices and Spring Cloud. For other short Spring Cloud tutorials, please check this page: Microservices and Spring Cloud for beginners.

Happy learning!

Leave a Reply

Your email address will not be published.