本项目使用springboot框架,并使用内嵌tomcat服务器,使用java -jar命令打包部署。
现需求是配置HTTPS
1、证书获取,这里现是测试研究阶段,采用工具自己生成。浏览器会提示不安全。
1)使用keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650命令,并按照提示输入相关信息。
2)在C盘的用户目录下,会自动生成证书
3)复制项目中,resources目录下
2、springboot中配置properties
在properties中添加如下配置
server.port=443 server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=password server.ssl.keyStoreType=PKCS12 server.ssl.keyAlias=tomcat
3、http重定向到https
配置两个bean,
import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * create by CP */ @Configuration public class HttpsConfig { @Bean public Connector connector(){ Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(80); connector.setSecure(false); connector.setRedirectPort(443); return connector; } @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; } }
4、测试
启动项目
通过浏览器访问 https://localhost ,即可转到
因为配置了http重定向,通过浏览器访问http://localhost亦可转到