简介
SSL(Secure Sockets Layer)是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络进行加密。SSL协议可以分为两层:SSL记录协议,为高层协议提供数据封装、压缩、加密,建立在TCP基础上;SSL握手协议建立在SSL记录协议之上,用于在实际数据开始传输之前,通信双方进行身份认证、协商加密算法、交换加密秘钥。
操作流程
生成证书
jdk自带的工具中,keytool是一个证书管理工具,可以用来生成自签名的证书。
keytool -genkey -alias tomcat
keytool -genkey -alias tomcat -keyalg "RSA" -keystore "test.keystore"
keytool -list -keystore test.keystore
keytool -delete -alias tomcat
运行完成后会在当前==用户目录==下声称.keystore文件,将对应的文件copy到resources目录下。
spring boot配置
server.ssl.key-store = .keystore
server.ssl.key-store-password = 123456
server.ssl.keyStroreType = JKS
server.ssl.keyAlias
http以及https支持
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat;
}
private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = new ClassPathResource("keystore").getFile();
File truststore = new ClassPathResource("keystore").getFile();
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
return connector;
}
catch (IOException ex) {
throw new IllegalStateException("can't access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
http协议自动转向https
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
return tomcat;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
Q&A
开启SSL之后在浏览器中访问,可能访问到的内容为空,主要是安全证书问题。有些浏览器存在安全证书问题时不会提示,不安全访问,而直接静止访问,可以更换一个浏览器试试。