springboot2使用ssl證書配置以及發佈

1、環境

阿里雲cenos 7.2
tomcat8.5.50
jdk1.8
阿里雲免費申請的ssl證書,tomcat下載:xxxx.pfx以及key.txt
web項目使用springboot2(springboot2以下的話SSLConfig的寫法不太一樣)

2、java項目中

1)新建一個 SSLConfig
在这里插入图片描述
2)代碼直接複製

package com.xxx.web.core.config;


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


@Configuration
public class SSLConfig {

    @Bean
    public TomcatServletWebServerFactory servletContainer() { //springboot2 新变化

        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(initiateHttpConnector());
        return tomcat;
    }

    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8952);        //http端口
        connector.setSecure(false);
        connector.setRedirectPort(9846);        //https端口
        return connector;
    }
}

3)把xxx.pfx放置到resources下
在这里插入图片描述
4)配置application.yml

server:
  # 服务器的HTTP端口,默认为80
  port: 9846
  ssl:
  #    证书路径
      key-store: classpath:xxx.pfx  # 证书的路径
      key-store-password: jQM******** # 证书密码,key.txt裏面的内容

然後編譯運行 https://localhost:9846 可以訪問
然後直接發佈到Linux就可以訪問了

3、結尾

阿里雲獲取到免費證書后我搜索了一系列 linux tomcat8.5下配置ssl證書的博客,并且也配置了,結果配置的那個端口只是讓tomcat首頁變成https訪問,所以無奈就換成這種思路最後才讓網站變成https可以訪問的,至於爲啥是繁體,win10更新后就這樣了,雖然輸入法顯示是簡體,真的狗屎
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值