Allow Only IP Address of Zuul API Gateway

In this tutorial I am going to share with you how to allow access to your Microservice from an IP address of Zuul API Gateway only.

In my previous tutorial, I have shared with you how to start up Zuul API Gateway and how to make it route HTTP Requests to Microservices registered with Eureka Discovery Service. When using Zuul API Gateway and Eureka, we want all HTTP Requests to be sent to a Zuul API Gateway rather than directly to a selected Spring Boot Microservice. Zuul API Gateway will accept all HTTP Requests, will authenticate user and will redirect HTTP Request to a specific Spring Boot Microservice registered via Eureka.

To prevent HTTP Requests coming from other sources than IP address of Zuul API Gateway, we can configure Spring Security in our Spring Boot Microservice and allow only a single IP address or a range of IP addresses to communicate with our Microservice. Below is how to do it.

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

Add Spring Security to Spring Boot Web Service

pom.xml dependency

Add the following pom.xml dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Once you add the above Spring Security dependency to pom.xml file of your Spring Boot project, Spring Security will be enabled for your project and user will need to be authenticated to be able to use it.

Grant Access From a Specific IP Address Only

Create a new configuration Java class, enable Web Security using the @Configuration and @EnableWebSecurity annotations. Then use the hasIpAddress(“192.168.2.81”) to allow access to your Web Service from specified IP address only.

package com.appsdeveloperblog.photoapp.api.users.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/**").hasIpAddress("192.168.2.81");
    }
    
}

Note: The IP address provided in hasIpAddress() should be an IP address if your Zuul API Gateway.

I hope this tutorial was helpful for you. If you are interested to learn more about Spring Cloud, have a look at the below list of video courses that teach Spring Cloud.