生成公钥和私钥
首先执行以下命令生成一个公钥和私钥(这里密码设置为password)
keytool -genkeypair -alias tomcat -keyalg RSA -keypass password -storepass password -keystore d:/server.keystore
关于keytool命令的说明 https://docs.oracle.com/javase/8/docs/technotes/tools/windows/keytool.html
tomcat配置ssl说明 https://tomcat.apache.org/tomcat-8.5-doc/ssl-howto.html
配置tomcat
修改tomcat的server.xml配置中Connector信息
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="d:\server.keystore" keystorePass="password" />
修改tomcat的web.xml中的配置
<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>Client Cert Users-only Area</realm-name>
</login-config>
<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>
关于使用https之后的小坑
后台通过request获取协议javax.servlet.ServletRequest#getProtocol 时不是返回https,而是返回http
public String getProtocol();
这里也说明了https并不是协议,只是针对http做了包装。(这里的s不是security,而是ssl)。 此时在前台构建路径的时候,就不能靠后台了
String contextPath = request.getContextPath();
String protocol = request.getProtocol();
protocol = protocol.substring(0, protocol.indexOf("/"));
int port = request.getServerPort();
String localBaseUrl = protocol.toLowerCase() + "://" + request.getServerName() + ":" + port + contextPath;
以上的代码最后拼接的请求路径会是http开头的而不是https,要解决此问题,直接在前台处理即可(window.location.protocol返回字符串’https‘)
var locProtocol = window.location.protocol;
var winLocalBaseUrl = window.localBaseUrl;
if ('https:' === locProtocol && winLocalBaseUrl && typeof winLocalBaseUrl == 'string'){
window.localBaseUrl = winLocalBaseUrl.replace('http:',window.location.protocol);
console.log("replace base url from " + winLocalBaseUrl + " to " + window.localBaseUrl);
}
如果是Spring Boot项目,使用嵌入式tomcat,只需要在配置文件中按照以下配置即可
server.port = 8443
server.ssl.key-store = classpath:sample.jks
server.ssl.key-store-password = secret
server.ssl.key-password = password
参考:https://github.com/spring-projects/spring-boot/tree/1.5.x/spring-boot-samples/spring-boot-sample-tomcat-ssl
|