Configure HTTP to HTTPS Redirect in Spring Boot

In the previous post, we have configured HTTPS in Spring Boot application. Today, we shall see how we can accept HTTP requests and redirect them to HTTPS.

Video guide of the process



Step 1 : Configure Redirect Connector.

Configure a connector, that will listen on port 80 for HTTP requests and redirect them to HTTPS on port 443, where HTTPS connector configured by Spring is listening to.

1
2
3
4
5
6
7
8
private Connector redirectConnector() {
return new Connector(Http11NioProtocol.class.getName()) {{
setScheme("http");
setPort(80);
setSecure(false);
setRedirectPort(443);
}};
}

Step 2 : Configure TomcatServletWebServerFactory Bean

Now, we need to configure TomcatServletWebServerFactory, which is used by Spring Boot to configure the embedded tomcat server.

Override the postProcessContext(Context context) method and add the securityConstraints of CONFIDENTIAL for all the requests.

Finally, we need to expose this factory as a Bean, so that Spring Boot uses it to create the embedded tomcat server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean
public TomcatServletWebServerFactory servletContainer() {
return new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
{
getAdditionalTomcatConnectors().add(0, redirectConnector());
}
};
}

Step 3 : Update TLS Port (Optional)

Update server.port to 443 in your application properties file as 443 is the default TLS port.

1
server.port=443

With this, the redirect connector configuration is done and you can verify by accessing the application using HTTP endpoint.

Go to your browser, type localhost and hit enter.

This will be redirected to https://localhost and you will see the Hello TLS / SSL response.