How to Redirect HTTP to HTTPS with Spring Boot
In this small tutorial I will show you how you can redirect the http traffic to https with yout spring boot application.
In the your Main Class, it should look like this:
... @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } ...
Add the following methods and variable declarations:
@Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @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); } }; tomcat.addAdditionalTomcatConnectors(createHttpConnector()); return tomcat; } @Value("${server.port.http}") private int serverPortHttp; @Value("${server.port}") private int serverPortHttps; private Connector createHttpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setSecure(false); connector.setPort(serverPortHttp); connector.setRedirectPort(serverPortHttps); return connector; }
In the appplication.properties file should be the following definitions
server.port=8443 server.port.http=8080
If you now start the application without any parameters, in will in the development stage, with port 8080 for http and 8443 for https.
To Start the application production stage you could start it like this:
java -jar springbootapplication.jar --server.port=443 --server.port.http=80
Done! – As easy as this.
Used Versions: Spring Boot v1.4.2.RELEASE) Apache Tomcat/8.5.6