关于springboot:Springboot配置https使用腾讯云免费证书

2次阅读

共计 1945 个字符,预计需要花费 5 分钟才能阅读完成。

1. 申请腾讯云收费 ssl 证书

1.1 登陆腾讯云在我的证书列表页面点击申请收费证书


2.2 提交材料,必填 证书绑定域名 以及 申请邮箱,绑定域名填写 springboot 我的项目部署的服务器域名

2.3 抉择验证形式,默认即可


2.4 验证域名,个别 2、3 分钟就验证结束了

2.5 验证结束后在证书列表页面下载证书文件,抉择 tomcat 目录下的 jks 文件即可

证书列表

证书压缩包文件

2. springboot 配置 ssl 证书

1.1 将 jks 文件导入 springboot 我的项目 resoures 目录下

2.2 在 application.yml 文件中配置如下代码

server:
  port: 443
  ssl: # ssl 相干配置
    enabled: true
    key-store: classpath:mall.wayn.ltd.jks
    key-store-password: idFXdK.Rnm3CgZp
    key-store-type: JKS

http-port: 8080 # http 重定向 https 配置

2.3 增加 HttpsConfiguration 文件,将 HTTP 申请重定向到 HTTPS

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.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpsConfiguration {@Value("${http-port}")
    private int port;

    @Value("${server.port}")
    private int sslPort;

    @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(port);
        connector.setSecure(false);
        connector.setRedirectPort(sslPort);
        return connector;
    }

}
  1. 拜访浏览器 http://localhost8080,会主动重定向到 https://localhost
正文完
 0