全站HTTPS升級系列(四)項目代碼升級改造

本文以msh.com 域名爲例css

1、修改頁面內的 HTTP 協議爲HTTPS協議

HTTPS 下不容許 HTTP 請求,若是有此狀況,則會在瀏覽器控制檯報以下錯誤前端

(index):42 Mixed Content: The page at 'https://b.test.iupiao.cn/' was loaded over HTTPS, but requested an insecure stylesheet 'http://at.alicdn.com/t/font_203680_of0yc4ur0ie.css'. This request has been blocked; the content must be served over HTTPS.
複製代碼

或者java

Mixed Content: The page at 'https://b.test.iupiao.cn/' was loaded over HTTPS, but requested an
複製代碼

錯誤緣由可能以下:nginx

  • 當前的HTTPS所承載的頁面,可是在頁面內引用了經過HTTP 協議訪問的靜態資源
  • 當前的HTTPS所承載的頁面,發送了請求路徑爲HTTP 協議的Ajax 異步請求

解決方案spring

將全部的HTTP 協議的URL全局替換爲HTTPS協議apache

2、 修改頁面內的ws協議爲wss協議

Nginx作全站HTTPS升級的時候,是不涉及到WebSocket相關的配置的後端

惟一須要作的,就是升級成功後,在前端代碼裏面把ws://協議替換爲wss://便可瀏覽器

想深刻了解的話,請參考這篇文章: WebSocket 和socket、HTTP的區別和聯繫安全

3、後端改造

本項目用Java做爲後端語言。在後端,經過SpringRestTemplate來作各個後端服務直接的數據請求bash

全站升級HTTPS後,RestTemplate 請求https路徑下的接口時會報錯,解決方式參見下方代碼

原理:

  • 把RestTemplate 的實例bean的生成方法重寫一遍,使之信任全部的安全證書
  • spring在實例化RestTemplate 的時候,會調用此方法,

把下面代碼放到任意一個spring管理下的service或者controller便可,以後spring裏面的全部的RestTemplate 實例就會經過此方法生成

@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(csf)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
}
複製代碼

系列文章

全站HTTPS升級系列(一)升級前的科普工做

全站HTTPS升級系列(二)基於 acme.sh從Letsencrypt生成免費的泛域名證書

全站HTTPS升級系列(三)nginx配置全站HTTPS

全站HTTPS升級系列(四)項目代碼升級改造

相關文章
相關標籤/搜索