How to restrict access to Spring Boot applications to a list of IP Addresses?

You can configure an Access Control List for IP Addresses in Spring Boot through the IPAddressAccessControlHandler. Let’ see how to do it.

@Bean public UndertowServletWebServerFactory embeddedServletContainerFactory() {
  UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
  factory.addDeploymentInfoCustomizers(new UndertowDeploymentInfoCustomizer() {
    @Override public void customize(DeploymentInfo deploymentInfo) {
      // Enable IPAddressAccessControlHandler
      deploymentInfo.addOuterHandlerChainWrapper(new HandlerWrapper() {
        @Override public HttpHandler wrap(HttpHandler handler) {
          return new IPAddressAccessControlHandler(handler).setDefaultAllow(false).addAllow("192.168.10.1").addAllow("192.168.10.2");
        }
      });
    }
  });
  return factory;
}

If you prefer, you can use the HandlerParser.parse() method to read the IP ACL:

@Bean public UndertowServletWebServerFactory embeddedServletContainerFactory() {
UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
factory.addDeploymentInfoCustomizers(new UndertowDeploymentInfoCustomizer() {
    @Override public void customize(DeploymentInfo deploymentInfo) {
      deploymentInfo.addOuterHandlerChainWrapper(HandlerParser.parse("ip-access-control(default-allow=false, acl={'192.168.10.1 allow', '192.168.10.2 allow'})", getClass().getClassLoader()));
    });
}
});
return factory;
}
Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon