I recently encountered a challenge when using the Spring Boot integration for Microsoft Entra (spring-cloud-azure-starter-active-director) behind a corporate proxy. It was a pain at first, but I solved the issue by customizing the RestTemplate used by the library. I’ll explain the problem in this post and share my implemented solution.
The Problem
The library makes HTTP requests to Microsoft Entra when using the Spring Boot starter. However, all outbound traffic in my environment must go through a proxy. The default configuration does not support proxies, which caused connection failures.
I tried to set the proxy using environment variables and Java system properties but this didn’t work. I was looking at the source code of the start project and found out that it’s using Spring’s RestTemplate
.
The Solution
To configure the proxy for the RestTemplate
this, I created a custom RestTemplateCustomizer
bean. This bean sets a custom SimpleClientHttpRequestFactory
that configures the proxy settings. The code snippet below shows how I achieved this:
public SecurityConfiguration(@Value("${https.proxy.host:localhost}") String proxyHost, @Value("${https.proxy.port:0}") int proxyPort) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; } @Bean public RestTemplateCustomizer restTemplateCustomizer() { return restTemplate -> { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); if (proxyHost != null && proxyPort > 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); factory.setProxy(proxy); } restTemplate.setRequestFactory(factory); }; }
Explanation
- RestTemplateCustomizer Bean: I defined a bean that customizes any
RestTemplate
instance. This is useful because the Azure starter is usedRestTemplate
for its HTTP calls. - Proxy Configuration: Inside the customizer, I check if
proxyHost
andproxyPort
are set. If they are, I create aProxy
object with these values. - Custom Request Factory: I then set this proxy on a
SimpleClientHttpRequestFactory
and update theRestTemplate
to use this custom factory.
By doing this, all HTTP requests made by the RestTemplate
go through the specified proxy, and the connectivity issues were resolved.
Lessons Learned
- Customizing Beans: Sometimes, you must customize the beans from third-party libraries to fit your network or environment requirements.
- Proxy Settings: When working in corporate environments, always ensure that your network settings (like proxy configurations) are correctly set up.
- Troubleshooting: Even simple configurations can become tricky when external factors (such as proxies) are involved. You can always check out the source code if you are using open-source software.
Conclusion
Configuring the Azure Spring Active Directory starter to work behind a proxy can be challenging, but with a small customization to the RestTemplate
, it is possible to overcome the issue. I hope this post helps anyone else facing a similar problem.