Appearance
Spring Boot:Web 配置自签名证书
在开发环境中,如果你的 Spring Boot Web 项目仅有内网 IP 地址,并且你希望为其配置 HTTPS,可以按照以下步骤进行操作:
1. 生成自签名证书
首先,你需要生成一个自签名证书。可以使用 keytool 工具来生成证书和密钥库文件。
Bash
keytool -genkeypair -alias myappkey -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore myapp.p12 -validity 365keytool 是 Java 提供的一个命令行工具,用于管理密钥库(keystore)和证书。keytool -genkeypair 命令用于生成一个新的密钥对(公钥和私钥)并将其存储在密钥库文件中。以下是命令的详细讲解:
命令参数讲解
-genkeypair:指示keytool生成一个新的密钥对(公钥和私钥);-alias myappkey:指定密钥对的别名。别名是密钥库中密钥条目的唯一标识符;-keyalg RSA:指定生成密钥对的算法。这里使用的是 RSA 算法;-keysize 2048:指定生成的密钥的大小(以位为单位)。这里密钥大小是 2048 位;-storetype PKCS12:指定密钥库的类型。这里使用的是 PKCS12 类型的密钥库;-keystore myapp.p12:指定生成的密钥库文件的名称。这里密钥库文件名是myapp.p12;-validity 365:指定生成的证书的有效期(以天为单位)。这里证书的有效期是 365 天;
以下是运行命令时可能的交互示例:
Bash
$ keytool -genkeypair -alias myappkey -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore myapp.p12 -validity 365
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]:
What is the name of your organizational unit?
[Unknown]:
What is the name of your organization?
[Unknown]:
What is the name of your City or Locality?
[Unknown]:
What is the name of your State or Province?
[Unknown]:
What is the two-letter country code for this unit?
[Unknown]:
Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
[no]: yes1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
通过以上步骤,你可以生成一个包含密钥对和自签名证书的密钥库文件 myapp.p12,并将其用于配置 Spring Boot 应用的 HTTPS。
2. 配置 Spring Boot 应用
将生成的
myapp.p12文件放置在你的 Spring Boot Jar 文件的同级目录。创建
application-dev.yml文件:yamlserver: port: 8443 ssl: key-store: file:./myapp.p12 key-store-password: your_keystore_password key-store-type: PKCS12 key-alias: myappkey一并放置在 Spring Boot Jar 文件的同级目录。
编写启动脚本
start.dev.sh:Bashjava -jar myapp.jar --spring.profiles.active="dev" --spring.config.additional-location=./运行脚本:
Bash./start.dev.sh