在适配微信小程序端的时候,微信官方必须要求使用HTTPS协议进行传输,所以需要给原有的后端服务支持https服务。
1、准备
- SSL证书,如果你在阿里云购买过域名,可以复制下面的网址到浏览器 https://common-buy.aliyun.com/?spm=5176.7968328.1266638..69bf12325DnJdQ&commodityCode=cas#/buy
点击下载,由于我们是部署在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;
}
说明:
-
- 如果项目只需要HTTPS,则可以将 位置1的地方删除,并且将 redirectConnector()方法删除;如果需要同时保留HTTP和HTTPS协议,则将 位置1 注释解开,并且需要注意的是, servletContainer()方法使用的端口号是yml中配置的端口号,所以在redirectConnector()方法中不能再使用相同的端口号,否则启动会失败。
- 同时开启HTTP和HTTPS,本质上就是开启两个tomcat,用来监听不同的端口请求。
4、配置postman支持HTTPS
之前看一些博客,需要配置一些信息才能进行访问,但是我测试的时候发现不需要更改任何配置就可以直接使用。下面是我的配置截图:
可以正常访问:
改成http协议就不行了
同理,访问https://www.baidu.com也是能访问到的