1.创建证书(这里使用jdk自带的keytools)
在cmd窗口,执行命令:
结果在指定路径下生成该文件:(文件名和存放路径是命令中定义的)
2.配置springboot
(1)将生成的server.keystore文件复制带项目根路径
(2)在application.properties文件中配置如下参数
#端口号
server.port=443
#生成的证书名称
server.ssl.key-store=server.keystore
server.ssl.key-alias=tomcat
server.ssl.enabled=true
#密钥库密码
server.ssl.key-store-password=123456
server.ssl.key-store-type=JKS
此时https就配好了,输入http://localhost:443/test,浏览器会提示需要 TLS
输入https://localhost:443/test才可正常访问
3.配置输入http自动跳转https
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){
@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(connector);
return tomcat;
}
@Bean
public Connector httpConnector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
现在输入http://localhost:8080/test 会自动跳转 https://localhost:443/test