配置如下:
- springboot启动的配置项,即yml中的server-port是http的端口,如果打算将http设为8081,将https设为8082,则将port设置为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
在后续更新中视为同一个值了,因此两者要设置为一样的密码