1、通过Keytool先建个证书,Keytool是一个Java 数据证书的管理工具,命令如下:keytool -genkeypair -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
具体含义不多解释。
2、将生成的证书文件keystore.p12放到工程的resources目录下。
3、在application.properties文件中增加配置信息如下:
server.port =8443
server.ssl.enabled =true
server.ssl.key-store =classpath:keystore.p12
server.ssl.key-store-password =mypassword
server.ssl.key-store-type =PKCS12
server.ssl.key-alias =tomcat
ok,启动你的应用,你的应用已支持https。
如果你想在通过http访问的时候重定向到https上可以增加以下代码
@Bean
public ServletWebServerFactory servletContainer() {
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(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector =new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
此处需要注意下,在spring boot1时的EmbeddedServletContainerFactory、TomcatEmbeddedServletContainerFactory在spring boot2中已经被干掉了。在spring boot2中要使用ServletWebServerFactory、TomcatServletWebServerFactory。
参考文档:
https://stackoverflow.com/questions/49324700/enable-https-with-self-signed-certificate-in-spring-boot-2-0
https://github.com/spring-projects/spring-boot/issues/9836
https://howtodoinjava.com/spring-boot/spring-boot-ssl-https-example/
http://code-adda.com/2018/06/07/enable-https-with-self-signed-certificate-in-spring-boot/
https://stackoverflow.com/questions/47700115/tomcatembeddedservletcontainerfactory-is-missing-in-spring-boot-2
网友评论