SpringBoot2. 0 supports HTTPS access

Time:2021-12-26

Bought dapideng COM, naturally HTTPS.

In fact, in previous blogs, the issue of configuring certificates has long been mentioned, but this time it has become springboot, which has a built-in Tomcat container, which is different from packaging the project under Tomcat.

The certificate is a free certificate applied by alicloud. It is placed under the resource directory and is a file ending in PFX.

In application Properties add the following configuration:

server.port=443
server.ssl.enabled=true
server.ssl.key-store=classpath:2046023_www.dapideng.com.pfx
server.ssl.key-store-password=c6503VGY
server.ssl.keyStoreType=PKCS12

Inject the following two beans into the application, which is also the part changed after springboot is updated to version 2.0. Most configurations from Baidu or Google are based on version 1.5.

@Bean
public Connector connector() {
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setScheme("http");
    connector.setPort(80);
    connector.setSecure(false);
    connector.setRedirectPort(443);
    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;
}

Execute the Maven command to package.

maven clean package

Send it to the server and execute the command to start the service in the background.

nohup java  -jar demo.jar &

SpringBoot2. 0 supports HTTPS access

Done,perfect~  👏👏

This work adoptsCC agreement, reprint must indicate the author and the link to this article

This paper consists oftelamiCreation, adoptionCC by 3.0 CN agreementFor permission, you can reprint and quote freely, but you need to sign the author and indicate it.

Recommended Today

Enable SSL for nginx under CentOS_ Sendfile support

LinuxsendfileSystem calls are the fastest way to send static files. By copying data directly in the kernel, it avoids the context switching between user state and kernel state caused by using read / write, and greatly improves the transmission efficiency. Nginx has supported it for a long timesendfileUse of instructions. However, switching between user mode […]