Tomcat配置https
1 生成Server端安全證書
要實現通信加密,首先要在本地准備一份符合X.509標准的Server端安全證書。如果有條件的話,可以向權威CA申請一份經過認證的安全證書(需要繁瑣的手續和金錢)。如果沒有條件的話,可以使用JDK提供的證書生成工具,在Windows命令行中操作如下:
C:\> keytool -genkey -keyalg RSA -keysize 1024 -sigalg SHA1withRSA -dname "cn=127.0.0.1,ou=product,o=nokia,c=CN" -validity 3650 -storepass nokia12345 -keystore c:\key.store
輸入<mykey>的主密碼
(如果和 keystore 密碼相同,按回車):(按回車)
這樣就在C:\目錄下生成了Server端的安全證書(key.store)。
備注:Linux下創建證書時,只需要更改上面命令的路徑信息,其余不變。
注意:
- 生成安全證書的工具keytool的參數validity表示證書的有效期,單位為天,需要根據實際需要配置。
- 作為Server端安全證書,CN字段必須與WEB應用的實際域名保持一致,否則會使客戶端報證書名稱不一致。
- 由於某些web容器的原因,keypass和storepass必須保持一致。
- 打開Tomcat安裝目錄下的/conf/server.xml文件。
- 修改http重定向到https的端口:
2 添加Server端安全證書
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="443" />
注意:不同的tomcat版本,其配置項可能有一定差別,請在原配置文件上修改藍色部分即可。
- 修改https參數
<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
ciphers="SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"
keystoreFile="c:/cert/key.store" keystorePass=" nokia12345 "
clientAuth="false" sslProtocol="TLS" />
注意:
keystoreFile參數的文件名請使用絕對路徑,keystorePass參數上的口令即storepas口令。
- 如果SSL不能正常啟動,可以指定使用Java Secure Socket Extension (JSSE),即將protocol="HTTP/1.1"修改為protocol="org.apache.coyote.http11.Http11Protocol"
3 配置需要強制使用SSL的目錄或文件
例如對於/SSL目錄下的所有文件和/test/login.jsp需要強制使用SSL,則編輯Tomcat對應web應用目錄下的WEB-INF/web.xml,在<web-app>節中加入如下配置:
<security-constraint>
<web-resource-collection>
<web-resource-name>SSL</web-resource-name>
<url-pattern>/SSL/* </url-pattern>
<url-pattern>/test/login.jsp</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
注意:
Web應用中,從https切換到http過程中會丟失session,無法保持會話的連續。解決的辦法就是用http-https-http過程代替https-http過程,保證會話的連續性。
4 重新啟動Tomcat
5 測試建議
- 在瀏覽器里輸入:https://xx.xx.xx.xx:8443,應能通過SSL正常訪問。
- 對於https切換到http頁面需要重點進行測試,檢查切換后會話是否中斷。
- 在手機終端上進行測試,看能否正常使用。(如果有手機終端用戶的話)。
- 使用SSL后,對性能會有影響,可進行性能測試。(可選)