spring boot 中启用 https
生活随笔
收集整理的這篇文章主要介紹了
spring boot 中启用 https
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>>
獲取證書
https 是加密鏈接. 是需要證書的. 那么證書從哪里取得呢? 在本地測試的時候, 可以自己生成一個 tomcat 的證書, 可以本地測試用.
生成方式配置方式見下面
tool -genkey -v -alias mykey -keyalg RSA -validity 3650 -keystore ./keystore在yml配置如下
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 的啟動類中. 添加如下代碼即可 ```
package wang.vchen.handling.config;import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /*** @Auther Vchen* @Description:* @Date: 20:56 2017/6/20.* @Modified:*/ @Configuration public class HttpsConfig {@Beanpublic EmbeddedServletContainerFactory servletContainer() {TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(){//1protected 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(httpConnector());return tomcat;}@Beanpublic Connector httpConnector(){Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");connector.setScheme("http");connector.setPort(8080);//表示用8080端口來供http訪問connector.setSecure(false);connector.setRedirectPort(8090);//自動重定向到8090端口return connector;} }這樣就可以實現 HTTPS 了
如果是測試環境的證書,瀏覽器可能會攔截,說是不安全的,需要將瀏覽器設置一下。
?
轉載于:https://my.oschina.net/kingchen8080/blog/994367
總結
以上是生活随笔為你收集整理的spring boot 中启用 https的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 玩lol电脑最佳配置是什么
- 下一篇: $.each()与$(selector)