Spring Boot項目配置阿里雲ssl證書

最近參與了一個微信小程序的項目,APIs要求服務器域名是Https的,所以學習了一下ssl證書在Spring Boot中的配置

首先,到雲服務提供商申請一套SSL證書,這裏就不提供具體的申請流程了

申請到證書之後下載證書
在這裏插入圖片描述
選擇Tomcat的進行下載,下載解壓後有兩個文件
在這裏插入圖片描述
分別是.pfx後綴和.txt後綴的

打開我們的項目(這裏就不演示如何構建自己的基於Spring Boot的項目了)
將.pfx文件放置在resources目錄下,和application.properties同級
在這裏插入圖片描述
打開application.properties文件
添加如下字段
在這裏插入圖片描述
其中

  • server.ssl.key-store.pfx文件的路徑
  • server.ssl.key-store-password是壓縮包中.txt文件的內容
  • server.porthttps訪問使用的端口
  • 其他兩項默認不用改

因爲Spring Boot不能同時使用HTTP和HTTPS,所以我們需要將HTTP的請求轉發給HTTPS

在SpringBoot2.x中使用配置如下

	//下面是2.0的配置,1.x請搜索對應的設置
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createHTTPConnector());
        return tomcat;
    }

    private Connector createHTTPConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        //同時啓用http(8080)、https(3036)兩個端口
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setPort(8080);
        connector.setRedirectPort(3036);
        return connector;
    }

附帶一個Spring Boot 1.x的
2.x版本中省去了postProcessContext方法的實現

@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(80);
        connector.setSecure(false);
        //監聽到http的端口號後轉向到的https的端口號
        connector.setRedirectPort(443);
        return connector;
    }

最後,打包部署到服務器就行了

部署好之後採用https訪問一下3036端口的swagger文檔
在這裏插入圖片描述
訪問成功

採用http訪問下http的端口8080
在這裏插入圖片描述
訪問成功

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章