.生成证书,可以使自签名或者从SSL证书授权中心获得的。
cmd进入JDK安装目录(D:\Java\jre1.8.0_181\bin),利用keytool证书管理工具,生成自签名证书。
生成命令如下(找不到keytoo命令的先去配置java环境)
我指定的名字叫tomcat.keystore 别名叫tomcat,密码自己设置,我这里用的tomcat,最后那个直接按得回车
keytoo命令:
keytool -genkey -alias tomcat -keyalg RSA -keystore D:/httpsKey/tomcat.keystore
2.SpringBoot配置SSL
将生成的自签名证书:tomcat.keystore拷贝到项目根目录下,与application.yml同级,如下图所示:
3.配置application.yml
server:
port: 8084
ssl:
key-store: classpath:tomcat.keystore #证书的路径
key-store-password: 123456 #证书密码,请修改为您自己证书的密码
key-store-type: JKS #证书类型(秘钥库类型)
key-alias: tomcat #证书别名
enabled: true #开启HTTPS
4.http访问自动转https访问
在启动类中添加如下两个方法,更改tomcat配置
@EnableSwagger2
@ComponentScan(basePackages = "com.guodi")
@SpringBootApplication
public class Application
extends SpringBootServletInitializer
{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* 将http请求变成https请求
* @return
*/
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
/**
* 将http请求变成https请求
* @return
*/
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(8083);
return connector;
}
}