springboot配置SSL自签名证书
1.证书生成
每一个JDK或者JRE里都有一个工具,叫做:keytool,安装了jdk或jre之后,配置好JAVA环境之后,就可以直接在控制台使用该命令生成自签名证书:
在控制台输入:
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore E:\Desktop\sslkey\keystore.p12 -validity 3650
命令参数说明:
1.-alias 证书别名
2.-storetype 指定密钥仓库类型
3.-keyalg 生证书的算法名称,RSA是一种非对称加密算法
4.-keysize 证书大小
5.-keystore 生成的证书文件的存储路径和文件名
6.-validity 证书的有效期
2.Spring Boot配置SSL
将证书复制到项目根目录,修改application.yml文件:
server:
port: 8443
ssl:
key-alias: tomcat
key-store-password: root123
key-store-type: PKCS12
key-store: classpath:keystore.p12
到这一步,已经可以通过HTTPS来访问Web了
3.HTTP自动转向HTTPS
在spring boot入口类中添加如下代码:
①spring boot1.x的配置:
// http转向https
@Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @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 connector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(8080); connector.setSecure(false); connector.setRedirectPort(8443); return connector; }
②springboot 2.x的配置:
@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(connector()); return tomcat; } @Bean public Connector connector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(8080); connector.setSecure(false); connector.setRedirectPort(8443); return connector; }