spring boot配置支持HTTPS协议并使用阿里云域名证书

在适配微信小程序端的时候,微信官方必须要求使用HTTPS协议进行传输,所以需要给原有的后端服务支持https服务。

1、准备

 点击下载,由于我们是部署在tomcat上,所以选择tomcat一行的下载

 

 下载之后有一个压缩包,解压之后里面有两个文件,.pfx就是证书文件,.txt的就是密码,等会配置的时候需要。

2、配置项目

  • 将上一部得到的pfx后缀的文件复制到resources目录

  • 配置yml文件
server:
  ssl:    key
-store-password: AOzksRxv #上一步txt文件中的字符串   key-store: classpath:imuster.pfx #证书位置   key-store-type: PKCS12       #证书类型
  • 修改pom文件,在打包的时候不要忘记.pfx文件
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.yml</include>
                    <include>imuster.pfx</include>
                </includes>
            </resource>
        </resources>
    <build>

3、在项目代码中新增注入相关bean

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/wx/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        //tomcat.addAdditionalTomcatConnectors(redirectConnector());        /// <---- 位置1
        return tomcat;
    }

    private Connector redirectConnector() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setPort(10900);
        connector.setScheme("http");
        connector.setSecure(false);
//        connector.setRedirectPort(10900);
        return connector;

}

  说明:

    1. 如果项目只需要HTTPS,则可以将 位置1的地方删除,并且将 redirectConnector()方法删除;如果需要同时保留HTTP和HTTPS协议,则将 位置1 注释解开,并且需要注意的是, servletContainer()方法使用的端口号是yml中配置的端口号,所以在redirectConnector()方法中不能再使用相同的端口号,否则启动会失败。
    2. 同时开启HTTP和HTTPS,本质上就是开启两个tomcat,用来监听不同的端口请求。

 4、配置postman支持HTTPS

  之前看一些博客,需要配置一些信息才能进行访问,但是我测试的时候发现不需要更改任何配置就可以直接使用。下面是我的配置截图:

 

 

 

 可以正常访问:

 

 改成http协议就不行了

 

 同理,访问https://www.baidu.com也是能访问到的

 

posted @ 2020-08-31 20:07  HMingR  阅读(872)  评论(0编辑  收藏  举报