在適配微信小程序端的時候,微信官方必須要求使用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也是能訪問到的