在springboot中配置https安装证书 Unable to Start embedded TomCat
来源:互联网 发布:windows副本不是正版 编辑:程序博客网 时间:2024/06/05 16:07
首先要获得http证书,可以向证书机构申请也可以自己制作根证书。在我当初配置https时一直报Unable to Start embedded TomCat的错误,后来仔细检查发现因为证书没和jar包放在一个根目录。然后添加如下代码设置证书配置即可
代码如下:
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.context.embedded.ConfigurableEmbeddedServletContainer;import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;import org.springframework.boot.context.embedded.Ssl;import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class WebConfig {@Beanpublic EmbeddedServletContainerCustomizer containerCustomizer() { return new EmbeddedServletContainerCustomizer() { @Override public void customize(ConfigurableEmbeddedServletContainer container) { Ssl ssl = new Ssl(); //Server.jks中包含服务器私钥和证书 ssl.setKeyStore("证书名"); ssl.setKeyStorePassword("密码"); container.setSsl(ssl); container.setPort(443); } };}//将http重定向至https@Beanpublic 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(80); connector.setRedirectPort(443); return connector;}}
阅读全文