证书生成
使用SSL需要我们先生成一个证书,这个证书我们可以自己生成,也可以从SSL证书授权中心获得。
命令生成证书生成JKS证书
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 1024 -validity 365 -keystore keystore.jks -keypass 123456 -storepass 123456
生成P12证书
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -validity 365 -keystore keystore.p12
-alias 别名 -keypass 指定生成密钥的密码 -keyalg 指定密钥使用的加密算法(如 RSA) -keysize 密钥大小 -validity 过期时间,单位天 -keystore 指定存储密钥的密钥库的生成路径、名称 -storepass 指定访问密钥库的密码
修改配置文件将证书文件添加到resources目录,并修改application.properties
server.port=443
server.http-port=80
#开启https,配置跟证书一一对应
server.ssl.enabled=true
#指定证书
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-type=JKS
#server.ssl.key-store=classpath:keystore.p12
#server.ssl.key-store-type= PKCS12
#别名
server.ssl.key-alias=tomcat
#密码
server.ssl.key-password=123456
server.ssl.key-store-password=123456
-
key-store:生成的证书文件的存储路径
-
key-store-password:指定签名的密码,要设置成刚刚你设置的密码
-
keyStoreType:为制定秘钥仓库的类型(PKCS12或者JKS)
-
keyAlias: 别名
如果不知道别名,可以在服务器中输入
keytool -list -keystore keystore.p12
配置http重定向https
在入口类中添加相应的转向Bean
@SpringBootApplication
public class TestDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestDemoApplication.class, args);
}
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(80);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(443);
return connector;
}
}