获取SSL证书有两种方式可以获取到SSL证书:(1)自己通过keytool生成;(2)通过证书授权机构购买;这里作为演示,采用keytool生成,实际项目中大部分采用的都是购买的方式。那么怎么
- 打开dos窗口;
- 输入如下命令:
keytool -genkey -alias tomcat -dname "CN=com.wxd,OU=kfit,O=kfit,L=HaiDian,ST=BeiJing,C=CN" -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 365-keystore keystore.p12 这里最好指定一下绝对路径,如果jdk装在c盘的会报错:keytool 错误: java.io.FileNotFoundException: keystore.p12 (拒绝访问。) Spring Boot中启用HTTPS 默认情况下Spring Boot内嵌的Tomcat服务器会在8080端口启动HTTP服务,Spring Boot允许在application.properties中配置HTTP或HTTPS,但是不可同时配置,如果两个都启动,至少有一个要以编程的方式配置,Spring Boot官方文档建议在application.properties中配置HTTPS,因为HTTPS比HTTP更复杂一些 在application.properties中配置HTTPS,配置信息如下:
#https端口号. server.port: 443 #http端口 server.http.port=8080 #证书的路径. server.ssl.key-store: classpath:keystore.p12 #证书密码,请修改为您自己证书的密码. server.ssl.key-store-password: 123456 #秘钥库类型 server.ssl.keyStoreType: PKCS12 #证书别名 server.ssl.keyAlias: tomcat注意:请将在上一步生成的证书放到src/main/resources目录下 将HTTP请求重定向到HTTPS
package com.neo.https.config; 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.beans.factory.annotation.Value; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author wxd * @version V1.0 * @description SpringSecurityConfiguration * @date 2022/4/22 14:16 **/ @Configuration public class HttpToHttpsContainerFactoryConfig { @Value("${server.http.port}") private int port; @Value("${server.port}") private int httpsPort; @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(httpConnector()); return tomcat; } private Connector httpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(port); connector.setSecure(false); connector.setRedirectPort(httpsPort); return connector; } }