SpringBoot开启https以及http重定向
一、使用JDK keytool创建SSL证书
进入$JAVA_HOME/bin目录,运行以下命令
keytool -genkey -alias WeChatAppletsDemo -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore D:/keys/weChat.keystore -storepass 123456
keytool
-genkey
-alias (别名)
-keypass (别名密码)
-keyalg (算法)
-keysize (密钥长度)
-validity (有效期,天单位)
-keystore (指定生成证书的位置和证书名称)
-storepass (获取keystore信息的密码)
在创建密钥的时候,算法记得将$JAVA_HOME/jre/lib/security/java.security文件中的keystore配置设置与命令一致
注意:keys文件夹需要提前创建,否则会报错
之后按提示进行操作,步骤如下:
二、为SpringBoot配置https
将生成的证书文件放入项目的resources文件夹中。
配置propertis文件
server.http.port属性用于开启http端口,将其重定向到https端口中
创建配置一个WebConfig类
package org.yoki.edu.portal.web.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.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Value("${server.port}") private int serverPort; @Value("${server.http.port}") private int serverHttpPort; /** * 解决跨域问题 * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT") .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers","accessToken") .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials") .allowCredentials(true).maxAge(3600); } @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(initiateHttpConnector()); return tomcat; } private Connector initiateHttpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); //需要重定向的http端口 connector.setPort(serverHttpPort); connector.setSecure(false); //设置重定向到https端口 connector.setRedirectPort(serverPort); return connector; } }
三、测试访问
访问http://localhost:8081将自动跳转到https://localhost:8433,如下图所示