配置如下:
- springboot啟動的配置項,即yml中的server-port是http的端口,如果打算將http設(shè)為8081,將https設(shè)為8082,則將port設(shè)置為https的8082,而http的端口用另一個配置項來配置,如:
server:
port: 8082 # HTTPS PORT
httpPort: 8081 # HTTP PORT
context-path: /demo
ssl:
key-store: classpath:my.keystore
key-alias: mykey
enable: true
key-store-password: mypass
key-store-type: JKS
配置類如下:
import lombok.Data;
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.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
@Data
@Configuration
public class SSLConfig {
@Value("${server.httpPort}")
int httpPort;
@Value("${server.port}")
int httpsPort;
@Bean(name = "connector")
public Connector connector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(httpPort);
connector.setSecure(false);
connector.setRedirectPort(httpsPort);
return connector;
}
@Bean
@DependsOn("connector")
public TomcatEmbeddedServletContainerFactory tomcatServletWebServerFactory(Connector connector){
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(connector);
return tomcat;
}
}
在IDE啟動成功,但是在linux利用java -jar命令啟動失??;報錯信息:
***************************
279 APPLICATION FAILED TO START
280 ***************************
281
282 Description:
283
284 The Tomcat connector configured to listen on port 5223 failed to start. The port may already be in use or the connector may be misconfigured.
285
286 Action:
287
288 Verify the connector's configuration, identify and stop any process that's listening on port 5223, or configure this application to listen on another port.
嘗試過各種方法都解決不了,最后還是StackOverflow靠譜:把yml的key-alias注釋掉
server:
port: 8082 # HTTPS PORT
httpPort: 8081 # HTTP PORT
context-path: /demo
ssl:
key-store: classpath:my.keystore
# key-alias: mykey
enable: true
key-store-password: mypass
key-store-type: JKS
原文:
Spring boot after https: The Tomcat connector configured to listen on port 8444 failed to start
其他原因可能是:
- 使用的密鑰keystore中,因為keytools把
keypass和storepass在后續(xù)更新中視為同一個值了,因此兩者要設(shè)置為一樣的密碼