首先下载证书

image-20211207202934469

文件解压缩之后得到一个后缀为pfx的证书文件 和 一个密码文本文件

image-20211207203350015

将后缀为pfx的证书文件放在resources目录下

image-20211207203404986

在application.yml文件中配置

# 80就是HTTP的端口,443就是https的端口
http:
  port: 80

server:
  port: 443
  ssl:
    key-store: classpath:文件名.pfx
    key-store-password: 密码
    key-store-type: PKCS12

当用户用http请求某个资源,而该资源本身又被设置了必须要https方式访问,此时Tomcat会自动重定向到这个redirectPort设置的https端口。

在springboot启动类中加入以下代码:

@Bean
public ServletWebServerFactory servletContainer() {
    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(redirectConnector());
    return tomcat;

}

private Connector redirectConnector() {
    Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
    connector.setScheme("http");
    connector.setPort(80);
    connector.setSecure(false);
    connector.setRedirectPort(443);
    return connector;

}

注意:

一定要把服务器中80和443端口打开
这里必须在服务器运行, 本地不能运行。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐