Configuring HTTPS in Spring Boot2

Keywords: Programming SSL JDK Tomcat Java

1. Generate certificate

Using jdk and keytool.exe in jre to generate self signed certificates requires the configuration of Java home and path environment variables, that is, jdk environment variables. The command is as follows:

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

Then you can find C: / user / user name / keystore.p12 and copy it to the spring boot project root directory

2. Add page and map

Add an index.html page under Resources / static

And add a configuration class MVCConfig

@Configuration
public class MVCConfig implements WebMvcConfigurer {
    public void addViewControllers(ViewControllerRegistry registry)         {
        registry.addViewController("/").setViewName("/index");
        registry.addViewController("/index").setViewName("/index");
    }  
}

3. Configure SSL with springboot

Configure in application.properties

server.port=8080
#SSL https certificate configuration
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=123456
#Industry standard PKCS12
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=tomcat

Now you can visit https://localhost:8080/index

4.http to https

Add the following code to MVCConfig

/*Configure http to https automatically*/
    @Bean
    public ServletWebServerFactory servletWebServerFactory(){
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");//Confidential
                SecurityCollection securityCollection = new SecurityCollection();
                securityCollection.addPattern("/*");
                securityConstraint.addCollection(securityCollection);
                context.addConstraint(securityConstraint);
            }
        };
        factory.addAdditionalTomcatConnectors(httpConnector());
        return factory;
    }

    @Bean
    public Connector httpConnector(){
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8888);
        connector.setSecure(false);
        connector.setRedirectPort(8080);
        return  connector;
    }

Remember that in springboot2 or above, without TomcatEmbeddedServletContainerFactory, it becomes TomcatServletWebServerFactory

Then go to http://localhost:8888/index and turn to https://localhost:8080/index

Posted by brianjw on Mon, 25 Nov 2019 09:57:34 -0800