springboot项目配置HTTPS

1.下载证书(使用的是阿里云的),springboot项目内置tomcat,所以下载tomcat版本的证书,下载的压缩包里有两个文件

  • -pfx后缀的文件 :证书
  • -pfx-password.txt :密码

2.将pfx后缀的文件放到项目resources路径下

3.在项目中的application.yml文件配置SSL

server:
  port: 443    									   #使用HTTPS时使用该端口
  ssl:                                             #配置HTTPS时打开
    key-store: classpath:xxxxx.pfx          	   #证书路径
    key-store-password: password                   #证书密码
    key-store-type: PKCS12                         #证书类型	

4.添加HTTPS配置类


```java 
@Configuration       
@Slf4j	
public class Http2HttpsConfig {

    @Bean
    public TomcatServletWebServerFactory 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;
    }

    /**
     * http 转发到 https
     * @return
     */
    @Bean
    public Connector httpConnector(){
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(80);
        connector.setSecure(false);
        connector.setRedirectPort(443);
        log.info("Http2HttpsConfig - 正式/生产环境通过https访问,启动443端口");
        return connector;
    }

}

5.项目使用websocket时,需要在页面将ws协议改成wss。

6.本地测试,打开C:\Windows\System32\drivers\etc目录下的host文件,在最后添加 127.0.0.1 www.xxx.com(证书对应域名),然后就可以在浏览器使用www.xxx.com域名进行测试(我主要是想测试HTML5中的Web Notification桌面通知功能)

待解决的问题:
1.application.yml配置中一些SSL配置不正确或多余的时候,springboot项目启动时会提示端口冲突
2.springboot项目启动时,如果找不到证书(证书位置不正确),也会提示端口冲突
3.目前把证书放在resources,yml配置了目录key-store: classpath:xxxxx.pfx classpath:xxxxx.pfx,启动也会提示端口冲突。
只好把证书放在项目根目录下,并将yml配置改成key-store: xxx.pfx
4.以上是前后端不分离的,项目前后端分离的时候,前端和后端都需要各自配置HTTPS,因为HTTPS的页面无法调用非HTTPS的接口或静态文件,不安全,会报错。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值