SpringBoot 如何配置 Https 以及 443端口被占用问题

1.生成 keystore 文件 

这里使用 jdk自带的keytool 命令 

keytool -genkey -alias your_password -keyalg RSA -keystore /home/local/fileName.keystore

2.在application.yml增加配置

server:
  port: 443
  ssl:
    key-store: classpath:server.keystore
    key-alias: fileName
    enabled: true
    key-store-password: you_password
    key-store-type: JKS

3.在config 类中增加 配置类

    @Bean
	@ConditionalOnExpression("'${spring.profiles.active}'.equals('pro')")
	public Connector connector(){
		Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setScheme("http");
		connector.setPort(8080);
		connector.setSecure(false);
		connector.setRedirectPort(443);
		return connector;
	}

	@Bean
	@ConditionalOnExpression("'${spring.profiles.active}'.equals('pro')")
	public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
		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(connector);
		return tomcat;
	}

4. 当你无论怎么启动 springboot 项目 都在报 443端口被 占用的时候

这里 你千万不要怀疑人生 其实很简单 是你yml文件 配置keystore位置出了问题

这里的地址配置 按照惯性思维 加上 classpath: 后面跟上你的 文件位置就好了

 key-store: classpath:server.keystore

猜你喜欢

转载自blog.csdn.net/weixin_41301898/article/details/89181836