背景
年末公司要進行年終促銷. 上一週時間都在弄年底促銷的玩意. 因爲用到了第三方的交易服務. 他們的 webhook 要求接口必須是 https. 之前沒有自己搞過 https. 剛好學習, 然後記錄下來.
獲取證書
https 是加密鏈接. 是需要證書的. 那麼證書從哪裏取得呢? 在本地測試的時候, 可以自己生成一個 tomcat 的證書, 可以本地測試用.
生成方式配置方式見下面.
keytool -genkey -v -alias mykey -keyalg RSA -validity 3650 -keystore ./keystore
server.port:8443
server.ssl.key-store: classpath:keystore.p12
server.ssl.key-store-password: xxxxx
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
但是本地生成的證書在生產環境是沒法用的. 第三方調用的時候是不 OK 的.
於是, 在阿里雲上找到了免費的證書申請.
購買後, 會有郵件發到註冊郵箱來認證的. 當然, 這裏要注意這個免費的證書只能用在一個域名下.
(不知道爲什麼用公司郵箱和個人郵箱, 這裏給出的認證方式不同. )
spring boot 配置
證書生成好之後, 下載之. 然後放在resources目錄下. 和 application.properties 並列.
阿里雲這個下載下來默認是pfx 格式的. 按照下面這樣配置就行:
server.ssl.key-store=classpath:1111111.pfx
server.ssl.key-store-password=1111111
server.ssl.keyStoreType=PKCS12
因爲是生產環境, 需要做 http 自動轉到 https. 所以這裏不配置端口號.
http 自動轉到 https
生產環境上 http 轉到 https 是一個很必要的能力.
在 spring boot 的啓動類中. 添加如下代碼即可
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
return tomcat;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setRedirectPort(443);
connector.setSecure(false);
return connector;
}
到這裏就全部結束了.