Skip to main content

Enable SSL for Development Environment - Spring BOOT



1) Generate Self signed SSL Certificate
     ==========================


  • keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -keystore keystore.jks -validity 3650
  • keytool -list -v -keystore keystore.jks
  • keytool -list -v -storetype pkcs12 -keystore keystore.p12
  • keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype pkcs12
  • keytool -export -keystore keystore.jks -alias tomcat -file myCertificate.crt


2) Copy keystore.p12 to java resource folder

3) Add the following to application properties


# Define a custom port instead of the default 8080
server.port=8443
# Tell Spring Security (if used) to require requests over HTTPS
security.require-ssl=true
# The format used for the keystore 
server.ssl.key-store-type=PKCS12
 # The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore.p12
 # The password used to generate the certificate
server.ssl.key-store-password=password //Given while generating the password
# The alias mapped to the certificate
 server.ssl.key-alias=tomcat

4) Add Connecter Config File

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConnectorConfig {

  @Bean
  public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat =
        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);
          }
        };
    tomcat.addAdditionalTomcatConnectors(redirectConnector());
    return tomcat;
  }

  private Connector redirectConnector() {
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setScheme("http");
    connector.setPort(8080);
    connector.setSecure(false);
    connector.setRedirectPort(8443);
    return connector;
  }
}

5) Clean, Build and Run the application, and check the 8443 port



Comments