欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot2配置https

程序员文章站 2022-04-27 18:43:49
...
  1. 添加配置类HttpsConfig.java

```java
		/**
		 * https SSL配置
		 */
		@Configuration
		public class HttpsConfig {
		
		    @Value("${server.http-port}")
		    Integer httpPort;
		
		    @Value("${server.port}")
		    Integer httpsPort;
		
		    @Bean
		    public ServletWebServerFactory servletContainer() {
		        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
		            @Override
		            protected void postProcessContext(Context context) {
		                SecurityConstraint constraint = new SecurityConstraint();
		                constraint.setUserConstraint("CONFIDENTIAL");
		                SecurityCollection collection = new SecurityCollection();
		                collection.addPattern("/*");
		                constraint.addCollection(collection);
		                context.addConstraint(constraint);
		            }
		        };
		        tomcat.addAdditionalTomcatConnectors(createHTTPConnector());
		        return tomcat;
		    }
		
		    private Connector createHTTPConnector() {
		        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		        connector.setProperty("relaxedQueryChars", "[]{}");
		        connector.setScheme("http");
		        connector.setSecure(false);
		        // http 端口 8080
		        connector.setPort(httpPort);
		        // https端口 server.port 必须一致 8443 否则 会报 端口被占用异常
		        connector.setRedirectPort(httpsPort);
		        return connector;
		    }
		}
  1. application.yml添加ssl配置
    如果证书别名与密码不正确也会报错
	#启动访问端口
		server:
		  port: 8443
		  ssl:
		    key-store: E:\ssl\cert\certhttps.pfx   # 也可以是其他文件格式
		    key-store-password: 123456
		    key-alias: certssl
		  http-port: 8080
  1. 如没有证书密码可利用jdk自带工具生成测试:

    cd jdk/bin 目录执行
    keytool -genkey -alias certssl -keyalg RSA -keysize 2048 -keystore E:\ssl\cert\certhttps.p12 -validity 3650

上一篇: 编码习惯

下一篇: || &&