Spring boot2 configures ssl to realize automatic transfer from HTTP access to HTTPS access

1. Generate a certificate. You can use self signed certificate or obtain it from SSL certificate authority center

In JDK, keytool is a certificate management tool, which can generate self signed certificates. Here, use the keytool provided by JDK to create certificate tests

Open cmd window, enter command

keytool -genkey -alias tomcat -keyalg RSA -keystore ./https.keystore

Follow the prompts

2. After creation, view the generated keystore file in the root directory of the user and copy it to the root directory of the project

3. Add configuration in yml file

4. Create another configuration class

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpsConfig {

    @Bean
    public Connector connector(){
        Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //The port number of the http that the Connector listens to
        connector.setPort(8080);
        connector.setSecure(false);
        //The port number of https after listening to the port number of http
        connector.setRedirectPort(8443);
        return connector;
    }

    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
        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(connector);
        return tomcat;
    }

}

5. Run the original address and jump automatically

Keywords: Tomcat Apache JDK SSL

Added by irishjohnny24 on Thu, 05 Dec 2019 06:36:58 +0200