這裏講的是 Spring Boot 內嵌式 Server 打 jar 包運行的方式,打 WAR 包部署的就不存在要 Spring Boot 支持 HTTPS 了,須要去外部對應的 Server 配置。java
更多請在Java技術棧微信公衆號後臺回覆關鍵字:boot。web
Spring Boot 配置 SSL 很簡單,只須要經過一系列的 server.ssl.*
參數便可完成配置,以下所示。spring
application.properties 配置文件參考配置:apache
server.port=8443 server.ssl.protocol=TLS server.ssl.key-store=classpath:javastack.keystore server.ssl.key-store-password=javastack server.ssl.key-store-type=JKS
如何在本地測試建立證書請參考Java技術棧微信公衆號的這篇文章《一分鐘開啓Tomcat https支持》,把生成完的證書複製到 Spring Boot 項目中的 resources 目錄便可。tomcat
這邊只是提供了一個 SSL 單向驗證的演示,更多 SSL 參數配置以下。微信
server.ssl.ciphers= # Supported SSL ciphers. server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. server.ssl.enabled= # Enable SSL support. server.ssl.enabled-protocols= # Enabled SSL protocols. server.ssl.key-alias= # Alias that identifies the key in the key store. server.ssl.key-password= # Password used to access the key in the key store. server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file). server.ssl.key-store-password= # Password used to access the key store. server.ssl.key-store-provider= # Provider for the key store. server.ssl.key-store-type= # Type of the key store. server.ssl.protocol=TLS # SSL protocol to use. server.ssl.trust-store= # Trust store that holds SSL certificates. server.ssl.trust-store-password= # Password used to access the trust store. server.ssl.trust-store-provider= # Provider for the trust store. server.ssl.trust-store-type= # Type of the trust store.
參數對應的類:org.springframework.boot.web.server.Sslapp
上面的例子配置後就能開啓 HTTPS 了,默認的 HTTP 協議就再也不支持了,Spring Boot 不支持以配置文件配置的方式同時支持 HTTP 和 HTTPS。運維
若是你須要同時支持 HTTP 和 HTTPS 這兩個協議,就須要把另一個協議用程序化的方式來配置。由於經過程序的方式配置 HTTP 協議更加簡單一點,因此,Spring Boot 推薦的作法是把 HTTPS 配置在配置文件,HTTP 經過程序來配置。ide
來,下面示例就是經過程序的方式來額外支持 HTTP 協議。源碼分析
@SpringBootApplication public class JavastackApplication { @Bean public ServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addAdditionalTomcatConnectors(createStandardConnector()); return tomcat; } private Connector createStandardConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setPort(8080); return connector; } public static void main(String[] args) { SpringApplication.run(JavastackApplication.class, args); } }
啓動 Spring Boot 以後就會看到下面的同時支持兩個協議日誌。
Tomcat started on port(s): 8443 (https) 8080 (http) with context path '/'
Spring Boot 支持 HTTPS 如此簡單,開發如今把運維的事都作了……
好了,今天的分享就到這裏,更多 Spring Boot 文章正在撰寫中,關注Java技術棧微信公衆號獲取第一時間推送。
在公衆號後臺回覆:boot,還能獲取棧長整理的往期 Spring Boot 教程,都是實戰乾貨,如下僅爲部分預覽。
本文原創首發於微信公衆號:Java技術棧(id:javastack),轉載請原樣保留本信息。