Spring Boot配置ssl证书

本文详细介绍如何在SpringBoot项目中集成SSL证书,包括从阿里云获取SSL证书、使用keytool工具转换证书格式,以及在SpringBoot项目中进行SSL配置的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:生成对应服务器容器可以识别的证书文件

在各大云服务商腾讯云,阿里云都可以申请到SSL官方证书。这里使用的是阿里云申请的ssl。

在这里插入图片描述

根据自身使用的服务器容器下载对应的证书到本地,这里使用Tomcat为例。解压后产生两个文件,一个为证书文件,一个为密钥文件

在这里插入图片描述

用JDK自带的keytool工具(一个证书管理工具),压缩成tomcat所支持的.jks,找到jdk安装目录下的bin目录下执行cmd,如果安装jdk时配置过环境变量则直接可以使用cmd命令。

在这里插入图片描述

执行命令压缩文件为tomcat所支持的.jks:

keytool -importkeystore -srckeystore C:\Users\Administrator\Desktop\新建文件夹\2540886_www.
xxxxxxx.com.pfx -destkeystore ssl.jks -srcstoretype PKCS12 -deststoretype JKS

C:\Users\Administrator\Desktop\新建文件夹\2540886_www. xxxxxx.com.pfx:表示证书所在目录地址,
ssl.jks:表示重新命名的名称。

在这里插入图片描述

输入对应证书的密码完成压缩,压缩生成的文件在bin目录找到 ssl.jks文件

在这里插入图片描述

在这里插入图片描述

2:springBoot项目中配置

将生成的文件复制到springboot项目resources目录下

.yml文件添加相应配置信息

server: 
  port: 443 #https端口号 443
  ssl:
    key-store: classpath:ssl.jks #证书路径 一定要加上classpath:
    key-alias: alias #证书别名,在jsk完成文件压缩时产生
    enabled: true #是否支持https
    key-password: abcdefg #对应SSL证书密码
    key-store-type: JKS #证书类型

添加让http重定向到https配置类“http:8080”重定向到“https:443”

package com.tizi.util;

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(8080);
    connector.setSecure(false);
    connector.setRedirectPort(443);
    return connector;
}
}

3:使用http,https分别测试,宣布Spring Boot配置ssl证书完成

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值