最近项目要使用https对请求加密,因为web服务使用的是tomcat,就整理了一下tomcat配置https环境的主要步骤:
1 打开cmd命令行,切换目录到jdk的bin目录下,执行以下命令
//使用jdk的加密工具,在目录e:\\intelStore_https路径下(确保此路径存在)生成server.keystore文件,服务端的证书,命令后半部分是证书的参数,
//keypass指定证书的密码,在此需要的是主意CN参数,指定服务所在机器的ip地址
keytool -keystore e:\\intelStore_https\\server.keystore -keypass 123456 -storepass 123456 -alias test1 -genkey -keyalg RSA -dname " CN=localhost" -validity 3650
//根据服务端认证server.keystore生成客户端认证证书server.cer
keytool -export -alias test1 -file e:\\intelStore_https\\server.cer -storepass 123456 -keystore e:\\intelStore_https\\server.keystore
//把客户端认证证书server.cer导入可信任库
keytool -import -file e:\\intelStore_https\\server.cer -storepass 123456 -keystore e:\\intelStore_https\\client.truststore -alias test1 -noprompt
2 修改tomcat配置
打开Tomcat 根目录下的 /conf/server.xml ,找到如下配置段,修改如下:
<Connector port="8443"
protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" disableUploadTimeout="true"
acceptCount="100" scheme="https" secure="true"
clientAuth="false"
keystoreFile="E:/intelStore_https/server.keystore" keystorePass="123456"
sslProtocol="TLS" />
keystoreFile指定服务器证书的路径
keystorePass是服务端证书的密码,即第一个cmd命令指定的密码
以上就是具体的配置,启动tomcat,访问https://localhost:8443时,页面上会提示此链接是一个不可信任的链接,在客户端导入上面配置生成的server.cer,设置成“受信任的证书”
主意:在上面命令指定CN时,一定要主意你的url的ip和CN指定的一定要保持一致,不然即使导入server.cer,设置成“受信任证书”也会提示链接不受信任!
3 如果想强制访问你的服务的链接一定是https请求,可以在你项目的web.xml加入如下配置:
<login-config>
<!-- Authorization setting for SSL -->
<auth-method>CLIENT-CERT</auth-method>
<realm-name>Client Cert Users-only Area</realm-name>
</login-config>
<security-constraint>
<!-- Authorization setting for SSL -->
<web-resource-collection >
<web-resource-name >SSL</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
========================================================================================================================
以上是windows服务器下的配置,下面是linux服务器上的配置:
1
[root@centos apache-tomcat-6.0.37]# keytool -genkey -alias tomcat -keyalg RSA -keystore /root/tomcat/apache-tomcat-6.0.37/conf/.keystore 输入keystore密码: 再次输入新密码: 您的名字与姓氏是什么? [Unknown]: free4lab 您的组织单位名称是什么? [Unknown]: free4lab 您的组织名称是什么? [Unknown]: free4lab 您所在的城市或区域名称是什么? [Unknown]: beijing 您所在的州或省份名称是什么? [Unknown]: beijing 该单位的两字母国家代码是什么 [Unknown]: CN CN=free4lab, OU=free4lab, O=free4lab, L=beijing, ST=beijing, C=CN 正确吗? [否]: y 输入<tomcat>的主密码 (如果和 keystore 密码相同,按回车):
2
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" keystoreFile="/root/tomcat/apache-tomcat-6.0.37/conf/.keystore" keystorePass="yourpassword" sslProtocol="TLS" />