当前位置: 首页 > news >正文

SpringBoot项目如何部署SSL证书 (JKS格式)

1、SpringBoot项目如何部署SSL证书 (JKS格式)

1. 获取 SSL 证书和私钥

首先,你需要获取有效的 SSL 证书和私钥。SSL 证书是一种用于加密通信的数字证书,它可以通过购买商业 SSL 证书或使用免费的 Let’s Encrypt 证书获得。请确保你拥有证书文件和与之对应的私钥文件,这通常是以 .pem 和 .key 结尾的文件或者是jks格式的,本文以jks格式的SSL证书为例。

2. 配置 Spring Boot 项目

接下来,我们将配置 Spring Boot 项目以使用 SSL。

2.0 项目环境

spring boot 2.2.2
maven
一个域名(各大域名商有售,阿里、腾讯、华为)
SSL证书(阿里云上有免费的SSL证书,有效期一年)

2.1 将 SSL 证书和私钥文件添加到项目

将之前获取的 SSL 证书和私钥文件拷贝到 Spring Boot 项目中的 src/main/resources 目录下。这样,证书文件会与项目一起打包并在运行时加载。
pPCuks1.png

2.2 配置 application.properties 或 application.yml

在 Spring Boot 项目的配置文件(application.properties 或 application.yml)中添加以下 SSL 相关配置:

server:port: 8856servlet:context-path: /ssl:enabled: true# 保存SSL证书的秘钥库的路径key-store: classpath:ssl/xxx.com.jkskey-store-password: xxx# 证书类型key-store-type: JKS
#    key-store-protocol: TLS

2.3 编写controller进行测试

添加一个controller,测试是否生效,测试结果如下:
pPCuAqx.png
通过上述访问发现,如果通过http访问会提示访问需要组合TLS,但是如果用户直接通过这种方式访问的话,存在着极差的用户体验。

2.4 编写配置类HTTP转HTPPS

当用户使用http访问的时候,将http协议重定向到https端口
(1)修改配置文件

custom:  # 自定义http启动端口http-port: 8857server:port: 8856servlet:context-path: /ssl:enabled: true#key-alias: alias-key # 别名(可以不进行配置)# 保存SSL证书的秘钥库的路径key-store: classpath:ssl/xxx.com.jkskey-store-password: xxx# 证书类型key-store-type: JKS
#    key-store-protocol: TLS

(2)添加配置类

package org.pp.ssl.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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** https配置,将http请求全部转发到https* @author P_P*/
@Configuration
public class HttpsConfig {@Value("${custom.http-port: 8857}")private Integer httpPort;@Value("${server.port}")private Integer port;@Beanpublic TomcatServletWebServerFactory servletContainer() {// 将http请求转换为https请求TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {@Overrideprotected void postProcessContext(Context context) {SecurityConstraint constraint = new SecurityConstraint();// 默认为NONEconstraint.setUserConstraint("CONFIDENTIAL");SecurityCollection collection = new SecurityCollection();// 所有的东西都httpscollection.addPattern("/*");constraint.addCollection(collection);context.addConstraint(constraint);}};tomcat.addAdditionalTomcatConnectors(httpConnector());return tomcat;}/*** 强制将所有的http请求转发到https** @return httpConnector*/@Beanpublic Connector httpConnector() {Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");connector.setScheme("http");// connector监听的http端口号connector.setPort(httpPort);connector.setSecure(false);// 监听到http的端口号后转向到的https的端口号connector.setRedirectPort(port);return connector;}
}

(3)启动项目
添加配置类之后,启动项目可以看到控制台出现了https端口和http端口
pPCugFU.png
再次访问测试接口,会发现地址栏出现了https
pPCuhl9.png

(4)同时开启http和https
如果不想将http请求都转发到https进行处理,可以同时开启http和https

/*** 同时开启http和https* @author P_P*/
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HttpsConfig {@Value("${custom.http-port: 8857}")private Integer httpPort;@Beanpublic TomcatServletWebServerFactory servletContainer() {TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();tomcat.addAdditionalTomcatConnectors(httpConnector());return tomcat;}@Beanpublic Connector httpConnector() {Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");connector.setPort(httpPort);return connector;}
}

这样访问8857(http协议)的端口就不会进行转发了
pPCuqYD.png

3、spring boot配置ssl证书,异常:Invalid keystore format

3.1环境介绍

springBoot中配置了一个bean,bean加载的时候,会进行jks的加载,jks文件放在src/resources下,然后就报错了,错误如下。

2023-08-03 22:22:27.261:[ERROR] [main:6839] [org.springframework.boot.SpringApplication.reportFailure:826] --> Application run failed 
org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat serverat org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:215)at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.startWebServer(ServletWebServerApplicationContext.java:297)at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:163)at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)at org.ee.authority.AuthorityApplication.main(AuthorityApplication.java:28)Caused by: java.lang.IllegalArgumentException: Invalid keystore formatat org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:99) ~[tomcat-embed-core-9.0.29.jar:9.0.29]at org.apache.tomcat.util.net.AbstractJsseEndpoint.initialiseSsl(AbstractJsseEndpoint.java:71) ~[tomcat-embed-core-9.0.29.jar:9.0.29]at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:218) ~[tomcat-embed-core-9.0.29.jar:9.0.29]at org.apache.tomcat.util.net.AbstractEndpoint.bindWithCleanup(AbstractEndpoint.java:1142) ~[tomcat-embed-core-9.0.29.jar:9.0.29]at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:1228) ~[tomcat-embed-core-9.0.29.jar:9.0.29]at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:586) ~[tomcat-embed-core-9.0.29.jar:9.0.29]at org.apache.catalina.connector.Connector.startInternal(Connector.java:1005) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
Caused by: java.lang.IllegalArgumentException: standardService.connector.startFailedat org.apache.catalina.core.StandardService.addConnector(StandardService.java:231)at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.addPreviouslyRemovedConnectors(TomcatWebServer.java:278)at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:197)... 10 common frames omitted
Caused by: org.apache.catalina.LifecycleException: Protocol handler start failedat org.apache.catalina.connector.Connector.startInternal(Connector.java:1008)at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)at org.apache.catalina.core.StandardService.addConnector(StandardService.java:227)... 12 common frames omitted
Caused by: java.lang.IllegalArgumentException: Invalid keystore formatat org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:99)at org.apache.tomcat.util.net.AbstractJsseEndpoint.initialiseSsl(AbstractJsseEndpoint.java:71)at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:218)at org.apache.tomcat.util.net.AbstractEndpoint.bindWithCleanup(AbstractEndpoint.java:1142)at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:1228)at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:586)at org.apache.catalina.connector.Connector.startInternal(Connector.java:1005)... 14 common frames omitted
Caused by: java.io.IOException: Invalid keystore formatat sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:666)at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:57)at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224)at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:71)at java.security.KeyStore.load(KeyStore.java:1449)at org.apache.tomcat.util.security.KeyStoreUtil.load(KeyStoreUtil.java:69)at org.apache.tomcat.util.net.SSLUtilBase.getStore(SSLUtilBase.java:217)at org.apache.tomcat.util.net.SSLHostConfigCertificate.getCertificateKeystore(SSLHostConfigCertificate.java:206)at org.apache.tomcat.util.net.SSLUtilBase.getKeyManagers(SSLUtilBase.java:283)at org.apache.tomcat.util.net.SSLUtilBase.createSSLContext(SSLUtilBase.java:247)at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:97)... 20 common frames omitted

3.2现象及原因分析

直接用main函数解析jks文件,一点毛病都没有。但是打包后启动Tomact再解析就不行,直接启动单元测试(完整加载bean的形式)也不行。

后来发现,在target文件夹下,jks文件的大小变了。查了资料,大概明白错误的根本原因了:maven编译或者打包的时候,对文件的内容进行了修改(maven编译的时候使用了占位符,替换的时候使文件发生了变化),这就导致了jks文件发生变化。

3.3解决方案

配置MAVEN过滤JKS等格式的文件,在pom的build配置中增加如下过滤配置,将jks过滤掉。(提一句,以下配置中也过滤了xlsx,是因为打包后Excel文件也会坏掉)

<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><configuration><encoding>${project.build.sourceEncoding}</encoding><useDefaultDelimiters>true</useDefaultDelimiters><includeEmptyDirs>true</includeEmptyDirs><!-- 证书文件 --><nonFilteredFileExtensions><nonFilteredFileExtension>pem</nonFilteredFileExtension><nonFilteredFileExtension>pfx</nonFilteredFileExtension><nonFilteredFileExtension>p12</nonFilteredFileExtension><nonFilteredFileExtension>key</nonFilteredFileExtension><nonFilteredFileExtension>xlsx</nonFilteredFileExtension><nonFilteredFileExtension>jks</nonFilteredFileExtension></nonFilteredFileExtensions></configuration></plugin><!-- java文档插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-javadoc-plugin</artifactId><version>3.0.0</version></plugin></plugins></build>

相关文章:

SpringBoot项目如何部署SSL证书 (JKS格式)

1、SpringBoot项目如何部署SSL证书 (JKS格式) 1. 获取 SSL 证书和私钥 首先&#xff0c;你需要获取有效的 SSL 证书和私钥。SSL 证书是一种用于加密通信的数字证书&#xff0c;它可以通过购买商业 SSL 证书或使用免费的 Let’s Encrypt 证书获得。请确保你拥有证书文件和与之…...

成功解决:ValueError Cannot assign non-leaf Tensor to parameter ‘weight‘

成功解决:ValueError Cannot assign non-leaf Tensor to parameter ‘weight‘ 欢迎大家来到安静到无声的《模式识别与人工智能(程序与算法)》,如果对所写内容感兴趣请看模式识别与人工智能(程序与算法)系列讲解 - 总目录,同时这也可以作为大家学习的参考。欢迎订阅,优…...

面试之快速学习SQL-基础增删改查语句

1. SELECT SELECT column1,column2,column3 FROM table_name;SELECT * FROM table_name;2. SQL SELECT DISTINCT 语句 在表中&#xff0c;可能会包含重复值。这并不成问题&#xff0c;不过&#xff0c;有时您也许希望仅仅列出不同&#xff08;distinct&#xff09;的值。 SE…...

nuxt脚手架创建项目

在初始化时遇到一个依赖找不到的问题&#xff0c;记录一下&#xff0c;如有遇到同样问题的小伙伴&#xff0c;希望能给你们一点指引。 从安装脚手架开始&#xff0c;首先 一&#xff1a;安装nuxt脚手架 1. C盘全局安装&#xff1a; npm i -g create-nuxt-app 安装后可creat…...

复现原型链污染漏洞

目录 一、复现原型链污染漏洞 hackit 2018 1、创建hackit_2018.js文件 2、运行hackit_2018.js文件 3、寻找原型链漏洞 4、污染原型链 hackit 2018 1、创建hackit_2018.js文件 const express require(express) var hbs require(hbs); var bodyParser require(body-par…...

.Net6 Web Core API 配置 Autofac 封装 --- 依赖注入

目录 一、NuGet 包导入 二、Autofac 封装类 三、Autofac 使用 四、案例测试 下列封装 采取程序集注入方法, 单个依赖注入, 也适用, 可<依赖注入>的地方配置 一、NuGet 包导入 Autofac Autofac.Extensions.DependencyInjection Autofac.Extras.DynamicProxy 二、Auto…...

鸿鹄工程项目管理系统em Spring Cloud+Spring Boot+前后端分离构建工程项目管理系统 em

​ Java版工程项目管理系统 Spring CloudSpring BootMybatisVueElementUI前后端分离 功能清单如下&#xff1a; 首页 工作台&#xff1a;待办工作、消息通知、预警信息&#xff0c;点击可进入相应的列表 项目进度图表&#xff1a;选择&#xff08;总体或单个&#xff09;项目…...

【搭建PyTorch神经网络进行气温预测】

import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.optim as optim import warnings warnings.filterwarnings("ignore") %matplotlib inlinefeatures pd.read_csv(temps.csv)#看看数据长什么样子 features.head…...

.Net6 Web Core API --- AOP -- log4net 封装 -- MySQL -- txt

目录 一、引入 NuGet 包 二、配置log4net.config 三、编写Log4net封装类 四、编写日志记录类 五、AOP -- 拦截器 -- 封装 六、案例编写 七、结果展示 一、引入 NuGet 包 log4net Microsoft.Extensions.Logging.Log4Net.AspNetCore MySql.Data ---- MySQL…...

【论文阅读】对抗溯源图主机入侵检测系统的模仿攻击(NDSS-2023)

作者&#xff1a;伊利诺伊大学芝加哥分校-Akul Goyal、Gang Wang、Adam Bates&#xff1b;维克森林大学-Xueyuan Han、 引用&#xff1a;Goyal A, Han X, Wang G, et al. Sometimes, You Aren’t What You Do: Mimicry Attacks against Provenance Graph Host Intrusion Detect…...

微信小程序多图片上传实用代码记录

微信小程序多图片上传实用代码记录 由于在小程序中&#xff0c;wx.uploadFile 只能一次上传一张图片&#xff0c;因此在一次需要上传多张图片的应用场景中例如商品图片上传、评论图片上传等场景下&#xff0c;不得不使用for等循环上传每一张图片&#xff0c;多次调用wx.upload…...

android实现获取系统全局对象实例

无需Context获取系统常用全局对象&#xff1a;Application&#xff0c;Activity&#xff0c;PackageManager等。 import android.app.Activity; import android.app.Application; import android.app.Service; import android.content.Context; import android.content.pm.Pac…...

viewerjs 如何新增下载图片功能(npm包补丁)

文章目录 先实现正常的效果实现下载图片改变viewerjs的build函数源码改变之后&#xff0c;执行npm i 之后node_modules源码又变回了原样 1、viwerjs所有功能都很完善&#xff0c;但唯独缺少了图片的下载 2、需求&#xff1a;在用viwerjs旋转图片后&#xff0c;可以直接下载旋转…...

基于YOLOv7开发构建MSTAR雷达影像目标检测系统

MSTAR&#xff08;Moving and Stationary Target Acquisition and Recognition&#xff09;数据集是一个基于合成孔径雷达&#xff08;Synthetic Aperture Radar&#xff0c;SAR&#xff09;图像的目标检测和识别数据集。它是针对目标检测、机器学习和模式识别算法的研究和评估…...

关于c++中mutable、const、volatile这三个关键字及对应c++与汇编示例源码

这哥三之间的关系是有趣的&#xff0c;不妨看看这个&#xff1a; cv (const and volatile) type qualifiers - cppreference.com mutable permits modification of the class member declared mutable even if the containing object is declared const. 即便一个对象是con…...

把大模型装进手机,分几步?

点击关注 文 | 姚 悦 编 | 王一粟 大模型“跑”进手机&#xff0c;AI的战火已经从“云端”烧至“移动终端”。 “进入AI时代&#xff0c;华为盘古大模型将会来助力鸿蒙生态。”8月4日&#xff0c;华为常务董事、终端BG CEO、智能汽车解决方案BU CEO 余承东介绍&#xff0c…...

c++游戏制作指南(三):c++剧情类文字游戏的制作

&#x1f37f;*★,*:.☆(&#xffe3;▽&#xffe3;)/$:*.★* &#x1f37f; &#x1f35f;欢迎来到静渊隐者的csdn博文&#xff0c;本文是c游戏制作指南的一部&#x1f35f; &#x1f355;更多文章请点击下方链接&#x1f355; &#x1f368; c游戏制作指南&#x1f3…...

Flutter系列文章-实战项目

在本篇文章中&#xff0c;我们将通过一个实际的 Flutter 应用来综合运用最近学到的知识&#xff0c;包括保存到数据库、进行 HTTP 请求等。我们将开发一个简单的天气应用&#xff0c;可以根据用户输入的城市名获取该城市的天气信息&#xff0c;并将用户查询的城市列表保存到本地…...

HCIA---TCP/UDP协议

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 目录 文章目录 一.UDP协议简介 UDP协议的特点&#xff1a; 二.TCP协议简介 TCP协议特点 三.TCP和UDP的区别 思维导图 一.UDP协议简介 UDP&#xff08;User …...

数据库索引的使用

1、MySQL的基本架构 架构图 左边的client可以看成是客户端&#xff0c;客户端有很多&#xff0c;像我们经常你使用的CMD黑窗口&#xff0c;像我们经常用于学习的WorkBench&#xff0c;像企业经常使用的Navicat工具&#xff0c;它们都是一个客户端。右边的这一大堆都可以看成是…...

Qwen2.5-Coder-1.5B应用案例:自动生成Bash脚本处理日志文件

Qwen2.5-Coder-1.5B应用案例&#xff1a;自动生成Bash脚本处理日志文件 1. 日志处理场景与痛点分析 1.1 运维工程师的日常挑战 在服务器运维工作中&#xff0c;日志分析是最常见也最耗时的任务之一。想象一下这样的场景&#xff1a; 你需要检查10台服务器上50个不同的服务日…...

别再被空白页坑了!用html2canvas + print-js打印Vue/React组件,保姆级避坑指南

彻底解决前端组件打印难题&#xff1a;html2canvas与print-js深度整合实践 在管理后台、数据报表等企业级应用中&#xff0c;精确打印特定组件是刚需&#xff0c;但现代前端框架的组件化特性让这个"简单需求"变得异常棘手。当你的Vue/React组件在屏幕上完美呈现&…...

【测试之道】第四篇:分层测试论 —— 金字塔、奖杯与蜂巢:构建你的质量防御阵型

专栏进度&#xff1a;04 / 10 (测试理论专题) 在不同的架构&#xff08;单体、微服务、前端驱动&#xff09;下&#xff0c;测试资源的分配比例是完全不同的。盲目套用模板是测试经理最容易犯的错误。 一、 经典模型&#xff1a;测试金字塔 (Testing Pyramid) 由 Mike Cohn 提出…...

工程伦理案例分析:从经典失败项目看责任分配与风险预防

工程伦理案例分析&#xff1a;从经典失败项目看责任分配与风险预防 当一座桥梁在通车典礼上轰然倒塌&#xff0c;当一栋新建大楼在台风中支离破碎&#xff0c;这些触目惊心的工程事故背后&#xff0c;往往隐藏着复杂的伦理困境。工程伦理不是简单的对错判断题&#xff0c;而是需…...

VCS编译SystemVerilog时,那个‘-P’选项你加对了吗?详解Verdi PLI配置

VCS编译SystemVerilog时&#xff0c;那个‘-P’选项你加对了吗&#xff1f;详解Verdi PLI配置 在芯片验证的日常工作中&#xff0c;VCSVerdi的组合堪称黄金搭档。但当你满怀信心地敲下编译命令&#xff0c;却发现怎么也生成不了关键的fsdb波形文件时&#xff0c;那种挫败感简直…...

JS 缓存函数(缓存函数计算结果、缓存异步函数的执行结果以及带过期时间)

JS 缓存函数 一、普通函数结果缓存&#xff08;同步缓存&#xff09; 实现一个通用缓存高阶函数&#xff0c;核心逻辑&#xff1a;第一次执行计算并缓存结果&#xff0c;后续相同参数直接读取缓存&#xff0c;不再重复执行。 实现代码 // 缓存高阶函数&#xff1a;接收一个函数…...

W25Q64 进阶应用:从电路设计到高效存储管理的实战解析

1. W25Q64硬件电路设计实战 第一次用W25Q64做项目时&#xff0c;我在电路设计上踩过不少坑。记得有个设备频繁出现数据丢失&#xff0c;最后发现是电源滤波没做好。这个8MB容量的SPI Flash芯片虽然引脚不多&#xff0c;但每个脚的设计细节都直接影响系统稳定性。 1.1 关键引脚…...

用Arduino Uno和纸板DIY一个超静音扫地机器人(附完整代码和接线图)

用Arduino Uno和纸板DIY一个超静音扫地机器人&#xff08;附完整代码和接线图&#xff09; 在宿舍或小公寓里&#xff0c;市售扫地机器人的马达噪音常常让人头疼。特别是对于学生和创客群体来说&#xff0c;既需要保持环境整洁&#xff0c;又不希望打扰到室友或邻居的休息。今天…...

厦门GEO软件哪家强?实测主流平台,为你揭秘推荐榜单

在数字化转型浪潮中&#xff0c;GEO&#xff08;地理定位优化&#xff09;软件成为企业提升本地化营销效率的关键工具。面对厦门市场上琳琅满目的GEO平台&#xff0c;如何选择一款适配自身业务需求、技术稳定且安全合规的解决方案&#xff0c;成为众多企业面临的难题。作为第三…...

Deep-Live-Cam实时换脸诊断指南:从启动失败到流畅运行的快速修复方案

Deep-Live-Cam实时换脸诊断指南&#xff1a;从启动失败到流畅运行的快速修复方案 【免费下载链接】Deep-Live-Cam real time face swap and one-click video deepfake with only a single image 项目地址: https://gitcode.com/GitHub_Trending/de/Deep-Live-Cam Deep-L…...