在springboot中配置https安装证书 Unable to Start embedded TomCat

首先要获得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;

@Configuration
public class WebConfig {
	@Bean
	public 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
	@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(80);
	    connector.setRedirectPort(443);
	    return connector;
	}
}


你可能感兴趣的:(java)