mkcert与springboot实现本地https测试

mkcert

mkcert可以用来生成pem证书,用于本地测试https.

安装:https://github.com/FiloSottile/mkcert/releases/latest (下载mkcert)

(安装成功后) 1.mkcert -install   2.mkcert localhost . 一次执行这两个命令获得pem文件(以localhost为域名)

pem转jks

tomcat中https可以用jks文件配置。需要把pem文件转成jks。可以使用openssl和keytool完成

命令: 
openssl pkcs12 -export -inkey ../localhost-key.pem -in ../localhost.pem -name localhost -out localhost.p12 (将pem文件转成p12文件 命令行会需要密码,记住这个输入的 密码)

keytool -importkeystore -srckeystore localhost.p12 -srcstoretype pkcs12 -destkeystore localhost.jks (p12转成jks文件)

SpringBoot配置https

把jks文件放在application.yml同级目录下,并修改application.yml如下:

#端口号
server.port: 8093
#你生成的证书名字
server.ssl.key-store= classpath:localhost.jks
server.ssl.key-store-password=123456
server.ssl.keyStoreType = JKS

http请求转https

此为spring2.0后的写法

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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;

@SpringBootApplication
public class HttpsApplication {

    public static void main(String[] args) {
        SpringApplication.run(HttpsApplication.class, args);
    }
    
    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的端口号
        connector.setPort(8080);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(8092);
        return connector;
    }

}

你可能感兴趣的:(随手小记,https,mkcert,springboot)