One way to ensure 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. 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.
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.
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.
- The first value is the name of the header. Which, in our case, is going to be “Authorization“. This is because we want the HTTP request to contain the Authorization HTTP header for this route to work.
- 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.
spring.cloud.gateway.routes.predicates=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 token, we can create a filter. And we can also validate the JWT token in the destination microservice.
Complete Route Configuration
Below is an example of a complete route configuration that uses the Header predicate.
spring.cloud.gateway.routes.id=users-status-check spring.cloud.gateway.routes.uri = lb://users-ws spring.cloud.gateway.routes.predicates=Path=/users/status/check spring.cloud.gateway.routes.predicates=Method=GET spring.cloud.gateway.routes.predicates=Header=Authorization, Bearer (.*) spring.cloud.gateway.routes.filters=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.