爲了提高系統的安全性,建議web程序都採用https方式部署,以下爲spring boot 2.1.1版本下的https的部署步驟
添加配置
server:
port: 443
ssl:
key-store: classpath:server.p12
key-store-password: 123456
key-store-type: PKCS12
http.port: 80
新建一個tomcat
新建一個tomcat的啓動bean,設置端口轉發(springboot會自動識別配置文件,ssl開啓後,會自動將server.port端口作爲ssl的端口部署)。
@Bean
public TomcatServletWebServerFactory servletContainer() { //springboot2 新變化
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@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(createHTTPConnector());
return tomcat;
}
private Connector createHTTPConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//同時啓用http(8080)、https(8443)兩個端口
connector.setScheme("http");
connector.setSecure(false);
connector.setPort(httpPort);
connector.setRedirectPort(httpsPort);
return connector;
}
驗證http端口的自動跳轉:
輸入訪問地址:http://localhost 訪問後自動跳轉 https://localhost 。