This post will discuss some of the ways to redirect HTTP requests to HTTPS in Spring Boot.

One of the common requirements for web applications is to redirect HTTP requests to HTTPS to ensure secure communication. There are several ways to achieve this in Spring Boot, depending on the configuration and preferences. Here are some of the common methods:

1. Using Spring Security

We can use the Spring Security framework to enforce HTTPS for all requests. We need to add the dependency org.springframework.boot:spring-boot-starter-security to our project and configure the security settings in application.properties file or in a Java class. For example, we can set the property security.require-ssl to true to enable Spring Security and force all requests to use HTTPS.

We can also use the HttpSecurity class to customize the port mapping and the channel security. For example, the following code uses the WebSecurityConfigurerAdapter class to customize the web security configuration and redirect HTTP requests on port 8080 to HTTPS requests on port 8443. It uses the portMapper() method to map the HTTP port to the HTTPS port and the requiresChannel() method to require HTTPS for all or some requests. We can also use the httpBasic() method to enable basic authentication.

2. Using WebServerFactoryCustomizer Interface

We can use this class to create a custom Connector that listens on a specific HTTP port and redirects requests to a HTTPS port. We need to implement the WebServerFactoryCustomizer interface and override the customize method to add the additional connector to the factory. For example, we can use the following code snippet to redirect HTTP requests on port 9090 to HTTPS requests on port 8443:

 
We also need to configure SSL for our embedded web server by using the server.ssl.* properties in our application.properties file (or in a Java class). For example, we can set the following properties to enable SSL with a PKCS12 keystore3:

server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:keystore/jimtough-dot-org-keystore.pkcs12
server.ssl.key-store-password=mykeystorepassword
server.ssl.key-alias=jimtough-dot-org
server.ssl.enabled=true
server.port=8443

That’s all about some of the ways to redirect HTTP requests to HTTPS in Spring Boot.