Springboot內建tomcat配置HTTPS證書

wuzhengxiansheng發表於2019-03-12

1.生成SSL證書

2.把證書放到專案根目錄下面,比如我之前給安信SSL網站安裝證書的時候,就放在:


3.把證書再放到專案resources目錄下,與application.properties同一目錄,然後修改application.properties檔案,新增HTTPS支援。在application.properties中新增如下程式碼:

Server:

Port:443指定https埠號

Server:

Key-store證書名稱

Key-alias別名

Key-store-type證書型別

Key-store-password證書密碼

Enabled: true允許透過https請求


4.在配置類中新增如下程式碼:

package com.bootdo.common.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.boot.context.embedded.ConfigurableEmbeddedServletContainer;

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;



@Configuration

public class HttpsConfig {

@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(getHttpConnector());

return tomcat;

}


private Connector getHttpConnector() {

Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");

connector.setScheme("http");

connector.setPort(80);

connector.setSecure(false);

connector.setRedirectPort(443);

return connector;

}

public void customize(ConfigurableEmbeddedServletContainer container) {

container.setPort(443);

}

}


5.上傳到伺服器的話,要在伺服器放jar包的地方壓放入證書檔案:

文章來源:


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69900059/viewspace-2638171/,如需轉載,請註明出處,否則將追究法律責任。

相關文章