I have a spring boot app running on GKE with the Google https load balancer via an ingress controller. The behavior I am looking for is for the Spring Boot app to redirect to https when an http request is received. In Spring Boot 2.2 and earlier I was able to do this with the following code and configuration.
configuration in my application yaml
server:
port: 8877
use-forward-headers: true # this should make it understand X-Forwarded-Proto header
and in my Spring Security configuration I did
@Override
protected void configure(HttpSecurity http) throws Exception {
/* When the app is running on GKE traffic will come in through the
* GCP http load balancer. Which will set the X-Forwarded-Proto
* header to http or https. When the app runs on a dev machine
* these headers are not set.
*
* see https://cloud.google.com/load-balancing/docs/https/
*
* The code forces ssl if the x forwarded proto header is present
* as that indicates the app is online and accessible to the
* wider internet.
*
*/
http.requiresChannel()
.requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
.requiresSecure();
// more stuff omitted
}
In Spring Boot 2.3 server.use-forward-headers
was deprecated I changed my config to be
server:
port: 7777
forward-headers-strategy: native
tomcat:
remoteip:
protocol-header: "X-Forwarded-Proto"
remote-ip-header: "X-Forwarded-For"
I made no changes to the code that requires Secure channel. However, when a request like https://example.com arrives at boot through the GCP load balancer it is not being recognized as a secure connection and a redirect https://example.com is sent from spring boot. This causes the browser to say that an infinite redirect loop has been detected.
Question What is the correct way to redirect from http to https on Spring Boot 2.3 running on GKE behind a GCP load balancer configured via and Ingress controller?