1. 程式人生 > >Tomcat實現https安全訪問

Tomcat實現https安全訪問

 點選下面連線檢視從零開始搭網站全系列

  由於國內的網路環境比較惡劣,運營商流量劫持的情況比較嚴重,一般表現為別人開啟你的網站的時候會彈一些莫名其妙的廣告...更過分的會跳轉至別的網站.

  那麼為了解決這種情況,那麼我們就要申請SSL證書,並且配置伺服器.

  並且,我準備再學習並寫一個微信小程式,而微信小程式所有介面都需要走https,那麼全線https就勢在必行.

  目前免費https其實有很多家,我之前出過一個教程是 用Let's Encrypt實現Https(Windows環境+Tomcat+Java) ,這個我現在也不準備用了,一是我現在開發環境從windows server換成了Linux,二是現在找到了更好用的免費SSL證書.

  我推薦大家使用兩家的免費SSL證書,一個是阿里雲的,一個是騰訊的(當然,實際上都是賽門鐵克的證書,我說他倆只是在他倆家可以免費買).免費的安全性,權威性肯定要差一點,但是我們個人建站掛個https就足夠了.如果有需要,這兩家有付費的更好的選擇.

  1:由於我是阿里雲重度依賴使用者嘛,所以我們先開啟阿里免費證書發放的網站: https://www.aliyun.com/product/cas?spm=5176.8142029.388261.255.b1KqKz

  或者可以在管理控制檯產品裡在這找到:

  2:點立即購買,選擇免費型:

  3:去支付-->立即付款-->跳轉至證書控制檯-->補全-->嗯...........................本地教程到此結束謝謝大家(開玩笑的下面還有)

  4:難道就因為這世界上有一個牌子是LV?所以我就不能給LV域名上SSL證書?還是因為綠綠?宗教歧視?阿里你這不清真啊,從你阿里旅行改名叫飛豬我就看出來了,你們阿里不是一家清真公司,哼!我們轉投騰訊好了.

  5:開啟騰訊雲證書管理頁面: https://console.qcloud.com/ssl 申請證書

  6:填寫子域名和申請郵箱,密碼和備註都可以不寫

  7:下一步,強烈建議選擇手動DNS解析,硬要選擇檔案驗證的...那你選吧我也攔不住...

  8:確認申請-->檢視證書詳情,如下圖所示:

  9:去你的域名DNS解析那裡新增一條這樣的解析,如下圖所示:

  10:返回你的證書列表,等人家給你發郵件和簡訊就行了,我申請的這兩都在1分鐘之內通過了,非常快速,差點圖都截不上了.

  11:證書申請好了,接下來該往tomcat裡配置了,這裡騰訊官方說的很明白,我就不獻醜了,直接上官方文件吧 : https://www.qcloud.com/document/product/400/4143#4.-tomcat-.E8.AF.81.E4.B9.A6.E9.83.A8.E7.BD.B2

  12:別急,還沒完,我這麼的男人,怎麼會到此結束了,下面還有很長呢

  13:好,大家現在想一個問題,經過第11步官方文件的配置,你所有請求都走了443埠,驗證了443埠所配的SSL證書了.可是.由於咱們申請的是單域名證書,而tomcat裡明明可以配置多域名多專案,目前來看一個埠只能配一個證書,那麼你其他網站怎麼辦,你其他有證書的域名怎麼往tomcat裡配呢?這就是我接下來要說的了----單tomcat,單ip,配多SSL證書

  14:網上的各種教程都是在要麼配多tomcat,要麼tomcat裡配多IP,這樣就可以有多個443埠,導致我一度認為實在是沒有辦法配單tomcat單SSL證書了.但是我之前知道nginx可以配置多SSL證書,我就去查了一下,原來原理是開啟SNI設定,那麼tomcat支不支援呢?經過查證,8.5以上的版本也支援SNI,這就很開心了(8.5以下是實在沒有辦法了,要不然你們升級tomcat版本跟我這個教程走,要不然再配一個nginx,請求先走ngnix代理一下)

  15:經過數小時的摸索,查閱了百度,谷歌等網站,由於tomcat9.0版本很新,使用的人很少(大多數人還是老版本不出錯就用老版本吶...),查到的資料比較少,結合一點點的資訊,再加上官方網站: http://tomcat.apache.org/tomcat-9.0-doc/config/http.html#SSL_Support_-_SSLHostConfig 和 https://tomcat.apache.org/tomcat-9.0-doc/ssl-howto.html 網站後,終於讓我的兩個證書都能在tomcat裡生效,在這裡我貼出我的server.xml 大家複製貼上過去,對應修改就好了,配置非常簡單(但是在除錯通之前是非常的痛苦,log的日誌資訊非常的少,中英文能參考的文獻也非常的少)

  配置ssl證書這裡,.jks檔案是騰訊雲提供給你下載的,把這個檔案放在伺服器/usr/tomcat/conf路徑下,後面那個密碼如果你在申請證書的時候填了就是那個,沒填就是下載下來跟.jks檔案在一起的另一個檔案.

複製程式碼

<?xml version='1.0' encoding='utf-8'?>
<!--
       Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
          define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
         <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
              Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
                  UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
              a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
             <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
                  and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="443" />

   <!-- A "Connector" using the shared thread pool-->
    <!--
             <Connector executor="tomcatThreadPool"
               port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
                  This connector uses the NIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->

    <Connector port="443" protocol="org.apache.coyote.http11.Http11Nio2Protocol" defaultSSLHostConfigName="www.lveri.com" 

               maxThreads="150" SSLEnabled="true" >

        <SSLHostConfig hostName="www.lveri.com">

            <Certificate certificateKeystoreFile="conf/www.lveri.com.jks" certificateKeystorePassword="x4f96s6l03152c" type="RSA" />

        </SSLHostConfig>

          <SSLHostConfig hostName="api.lveri.com">

              <Certificate certificateKeystoreFile="conf/api.lveri.com.jks" certificateKeystorePassword="ei25vtm4ag" type="RSA" />

          </SSLHostConfig>

    </Connector>


    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
                  every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
             <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
                     /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
                 <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
                      via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
                          resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
                                                                             
      </Realm>
        <Host name="www.lveri.com"  appBase="webapps" unpackWARs="true" autoDeploy="true"><Context path="" docBase="lveri" reloadable="true" debug="0" /></Host>
        <Host name="api.lveri.com"  appBase="webapps" unpackWARs="true" autoDeploy="true"><Context path="" docBase="lveri" reloadable="true" debug="0" /></Host>
    </Engine>
  </Service>
</Server>