https单向认证及tomcat配置https方法

时间:2022-05-16 15:14:43

在tomcat的bin目录或jdk的bin目录下面执行:
第一步:为服务器生成证书

keytool -genkey -v -alias tomcat -keyalg RSA -validity 3650 -keystore E:\tomcat.keystore -dname "CN=localhost,OU=cn,O=cn,L=cn,ST=cn,c=cn" -storepass 123456 -keypass 123456 

CN=localhost 中的localhost为域名或地址栏输入的IP地址

第二部:修改 tomcat 配置 

<!--修改conf/server.xml-->
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreFile="E:\\tomcat.keystore" keystorePass="123456" truststoreFile="E:\\tomcat.keystore" truststorePass="123456"/>

第三部.导出证书文件并导入到浏览器中

keytool -export -alias tomcat -file E:/file.cer -keystore E:/tomcat.keystore -validity 36500

输入刚才设置的证书库密码就可以导出证书文件。
生成的cer文件双击即可添加。

第四部。配置http重定向到https
在应用程序中web.xml中加入

<security-constraint>

        <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>

第五步。验证

1.https://localhost:8443/demo/ 访问成功
2.http://localhost:8080/demo/ 会自动跳转到 https://localhost:8443/demo/ 访问成功