秒懂https之如何在SpringBoot2中使用自签名证书

【版权申明】非商业目的注明出处可自由转载
博文地址:
出自:shusheng007

系列文章:
秒懂Https之CA证书与自签名证书漫谈
秒懂Https之如何在Android中使用自签名证书

概述

秒懂Https之CA证书与自签名证书漫谈中我们谈到了如何生成自签名证书的问题,在秒懂Https之如何在Android中使用自签名证书中又谈到了如何在Android中使用自签名证书。本文我们一起来看一下,如何在SpringBoot2中使用自签名证书。

闪光点

事先声明一下,这个闪光点是我自己认为的,因为它困扰了我很久。关于如何在springboot2中配置https网上有很多很好的文章,照着做一般也没有问题。但是当我将本地成功运行https的程序部署到服务器的Tomcat后发现https不起作用。最后我才发现在springboot2中的那顿配置原来是在配置其内置的那个Tomcat!我是真的不知道,此处允许鄙视我!

配置SpringBoot2内置的Tomcat

  1. 将证书容器(例如我的是keystore.p12)放到src/main/resources文件夹下

  2. application.properties文件中配置tomcat的属性
    假设我生成证书命令如下

    keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650 -ext san=ip:192.168.xx.xx -storepass pw12345
    

    那么配置就如下

    server.port=8443
    server.ssl.key-store= classpath:keystore.p12
    server.ssl.key-store-password= pw12345
    server.ssl.key-password= pw12345
    server.ssl.key-store-type= PKCS12
    server.ssl.key-alias= tomcat 
    

    完成上面两步其实已经可以了,但是有一个问题,就是现在你的服只支持https而不支持http请求了。

  3. 同时支持http与https请求

    在你的project中新建一个配置类,注意使用@Configuration标记

    @Configuration
    public class ServerConfig {
        @Bean
        public ServletWebServerFactory servletContainer() {
            TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
                @Override
                protected void postProcessContext(Context context) {
                    //使用CONFIDENTIAL模式,Tomcat会将所有的请求都使用HTTPS,
                    SecurityConstraint securityConstraint = new SecurityConstraint();
                    securityConstraint.setUserConstraint("CONFIDENTIAL");
                    SecurityCollection collection = new SecurityCollection();
                    collection.addPattern("/*");
                    securityConstraint.addCollection(collection);
                    context.addConstraint(securityConstraint);
                }
            };
            tomcat.addAdditionalTomcatConnectors(getHttpConnector());
            return tomcat;
        }
    
        private Connector getHttpConnector() {
            Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
            connector.setScheme("http");
            connector.setPort(8888);
            //如果 connector.setSecure(true) 同时支持http和https
            //如果 connector.setSecure(false) http的请求会重定向到https
            connector.setSecure(true);
            connector.setRedirectPort(8443);
            return connector;
        }
    }
    

    关于connector.setSecure(true) 的效果建议自己试一试。

总结

如果你的项目要发布成可以执行的jar,这些配置都是有意义的,是会影响最终结果的。但是如果你发布为war 然后部署到单独的tomcat上,那么你就需要去配置那个tomcat了,这块的配置仅仅是在配置springboot内置的tomcat,和你部署的那个毛关系没有。

关于如何配置tomcat支持https,下篇文章再说,掌声该起了…

成名每在穷苦日,败事多因得意时。

猜你喜欢

转载自blog.csdn.net/ShuSheng0007/article/details/107968779
今日推荐