Spring boot enables SSL security verification (two ports cannot be configured in application.properties)

1) Enable SSL (HTTPS)
By default, SpringBoot starts the HTTP service on port 8080. The HTTPS service on port 8443 can be enabled by the following configuration.
src/main/resources/application.properties
server.port=8443
server.ssl.key-store=keystore.p12
server.ssl.key-store-password=password
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat


But Spring Boot does not support both HTTP and HTTPS via application.properties.
This can be achieved by setting HTTPS in application.properties and adding Connector support for HTTP in the code.

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.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * https configuration
 *
 */
@Configuration
public class SSLConfig {

    @Value("${server.ssl.urls}")
    String urls;
    @Value("${server.non-ssl-port}")
    int port;
    @Value("${server.port}")
    int sslPort;
    // configure port 8080 service
    @Bean
    public EmbeddedServletContainerFactory servletContainer(Connector httpConnector) {
        TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                if(!StringUtils.isEmpty(urls)) {
                    String[] urlArr = urls.split(",");
                    for(String url : urlArr) {
                        collection.addPattern(url);
                    }
                }
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        container.addAdditionalTomcatConnectors(httpConnector);
        return container;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(port);
        connector.setSecure(false);
        // Jump to SSL verification
        connector.setRedirectPort (sslPort);
        return connector;
    }
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326540362&siteId=291194637
Recommended