Springboot配置https证书

2020-04-24 / 4 阅读 / Java

准备

  1. Springboot: 2.1.2.RELEASE

  2. 证书是阿里云免费证书,申请后可下载各种版本

实例

可将证书文件放置resources目录下,正式环境建议在固定目录存放

代码如下,亲测可行:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

     ...

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();

        // 基本参数
        String keyStore = "1754557_www.wbsite.xyz.pfx";
        String keyStorePassword = "****";
        String keyStoreType = "PKCS12";
        int httpsPort = 443;

        File keystore = null;
        // 正常开发可以通过getFile()获取,打包jar后无法直接获取File对象,需将文件考出
        try {
            keystore = new ClassPathResource(keyStore).getFile();
        } catch (IOException ex) {
            try {
                ApplicationHome home = new ApplicationHome(getClass());
                // 当前运行jar文件
                File jarFile = home.getSource();
                //jar同目录
                keystore = new File(jarFile.getParent(), keyStore);

                InputStream inputStream = new ClassPathResource(keyStore).getInputStream();
                byte[] bytes = new byte[inputStream.available()];

                inputStream.read(bytes);

                inputStream.close();

                FileOutputStream fileOutputStream = new FileOutputStream(keystore);
                fileOutputStream.write(bytes);
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 创建Connector
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        connector.setScheme("https");
        connector.setSecure(true);
        connector.setPort(httpsPort);
        protocol.setSSLEnabled(true);
        protocol.setKeystoreFile(keystore.getAbsolutePath());
        protocol.setKeystorePass(keyStorePassword);
        protocol.setKeystoreType(keyStoreType);

        // 添加
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }
}
相关推荐