[SSL]——如何使用SpringBoot内置的tomcat配置SSL——>从而实现HTTPS访问(基于阿里云云服务器)

最近一直在搞微信小程序,然后我是负责后端接口的设计,功能的实现。

因为小程序中请求接口需要https格式。

第一次研究这个,搞了今天一天,虽然走了很多弯路! 不过! 现在发现! 很简单的!

​​​​​​​大概介绍

  • 下载SSL证书,因为我用的是阿里云服务器,所以就直接从阿里云申请了免费的证书

  • 将证书复制到项目中并进行配置

一:SSL证书 

 因为我是用了springboot内置的tomcat,所以下载的就是tomcat版本的证书;

一个pfx文件,一个pfx密码文件

二:项目配置

打开项目目录,在src->main->resources中,把我们上面的两个文件放进去

接下来就是修改application配置文件,application配置文件有两种格式properties和yml ;

内容都相同,但就是格式不同;并且千万不要混用!

我项目文件使用的yml,我将properties的也写在下面。

application.yml添加的内容如下:

server:
    port: 443   #https的默认端口就是433 不能修改
    ssl:
        key-store: classpath:3516608_www.shiwanfute.cn.pfx   #证书pfx的名字
        key-store-type: PKCS12                               #证书的类型
        key-store-password: ********                         #pfx-password.txt中的密码

application.properties添加的内容如下: 

三:如果也要使用http,可以加入以下代码,将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.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;

/**
 * http重定向到https
 * @return
 */
@Configuration
public class SecurityConfig
{
    @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(httpConnector());
        return tomcat;
    }

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

}

四:将项目打包成jar包

打开项目文件夹-->targer文件夹,就可以看到jar包啦

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值