1.自己生成keystore->将csr文件申请证书颁发机构->证据机构返回crt证书->配置到spring boot框架中
1.需要一个证书,可以自己生成或者购买。下面是我们通过keytool自己生成。
生成命令: keytool -genkey -alias tomcat -keyalg RSA -keystore name.keystore
然后按照提示填信息,可以随便写,但要记住(特别是别名,密码)
会在当前目录生成一个name.keystore的证书.
其中tomcat是别名 可以随便起,name.keystore也是随便起,其中keystore是后缀不能改
2. 导入证书(买的cer证书)
keytool -import -trustcacerts -alias tomcat -file intermediate.cer -keystore name.keystore
此时会报 “回复中的公共密钥与密钥库不匹配”错误
原因是 导入时的别名 tomcat 与 第1步的生成证书时的别名tomcat重复
别名改一下别重复就行。
比如将tomcat改为tomcat1 如下:
keytool -import -trustcacerts -alias tomcat1 -file intermediate.cer -keystore name.keystore
3.将name.keystore文件拷贝到项目的classpath路径中
4.在application.properties中配置HTTPS
server.port=8843
server.ssl.key-store=intel.keystore
server.ssl.key-alias=tomcat
server.ssl.key-password=123456
server.ssl.key-store-type=JKS
到这儿就改为支持https了
5.如果想再兼容http,在webconfig文件中 加入如下代码:
@Configuration public class WebConfig { @Bean public EmbeddedServletContainerFactory servletContainerFactory() { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { //SecurityConstraint必须存在,可以通过其为不同的URL设置不同的重定向策略。 SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; factory.addAdditionalTomcatConnectors(createHttpConnector()); return factory; } private Connector createHttpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setSecure(false); connector.setPort(8080); connector.setRedirectPort(8843); return connector; } }
这就是默认当http请求时,自动重定向到https请求中去!
这就完成了SpringBoot的HTTPS协议配置,重新启动后访问https://localhost:8443/proName 即可