玖叶教程网

前端编程开发入门

SpringBoot2.x开启Https协议

springBoot2.X 支持http、https访问

1.第一步 生成https证书

打开cmd

keytool -genkey -alias tomcat -keyalg RSA -keysize 2048 -validity 365 -keystore keystore.p12 -keypass 123456 -storepass 123456 -dname "CN=xingming,OU=danwei,O=zuzhi,L=shi,ST=sheng,C=CN"

2.第二步 将证书复制到项目的 resources 目录下 添加SSL配置



http:
  port: 80
server:
  port: 443
  ssl:
    enabled: true
    key-alias: tomcat
    key-store: classpath:keystore.p12
    key-store-password: 123456
    key-store-type: JKS

3.如果只是想变成https访问 上面步骤已经足够 如果还需要配置http访问 新增配置文件

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.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TomcatConfig {
    // 在某配置类中添加如下内容
    // 监听的http请求的端口,需要在application配置中添加http.port=端口号  如80
    @Value("${http.port}")
    Integer httpPort;

    //正常启用的https端口 如443
    @Value("${server.port}")
    Integer httpsPort;

    // springboot2 写法
    @Bean
    public TomcatServletWebServerFactory 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(httpConnector());
        return tomcat;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的端口号
        connector.setPort(httpPort);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(httpsPort);
        return connector;
    }

}

4. 附上测试截图

5.购买了阿里ESC实例的可以阿里云申请免费的SSL证书 替换上面自己生成的证书即可 证书别名可以注释掉


发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言