java net 配置局域网受信任的https

135 阅读1分钟

安装 Chocolatey(Windows 包管理器

Windows PowerShell ISE 安装Chocolatey

Set-ExecutionPolicy Bypass -Scope Process -Force;
\[System.Net.ServicePointManager\]::SecurityProtocol =
\[System.Net.ServicePointManager\]::SecurityProtocol -bor 3072; iex
((New-Object
System.Net.WebClient).DownloadString(\'https://community.chocolatey.org/install.ps1\'))

验证安装

choco \--version

使用 choco 安装 mkcert

[在管理员 PowerShell 中运行:]{.mark}

choco install mkcert

验证 mkcert 是否正常

mkcert -install

然后为你的局域网 IP 生成证书(例如 192.168.5.31):

mkcert 192.168.5.31

这时候会得到2个文件

192.168.5.31.pem
192.168.5.31-key.pem

asp.net core 启动设置证书

使用openssl 将文件转成 pfx

openssl pkcs12 -export -out server.pfx -inkey 192.168.5.31-key.pem -in
192.168.5.31.pem -name \"192.168.5.31\" -password pass:yourpassword123

代码配置

// 配置 Kestrel 使用 HTTPS 证书

builder.WebHost.ConfigureKestrel(serverOptions =>
{
    var pfxPath = Path.Combine(builder.Environment.ContentRootPath, "certs", "server.pfx");
    var pfxPassword = "yourpassword123"; 
    if (File.Exists(pfxPath) )
    {
        serverOptions.Listen(new IPEndPoint(IPAddress.Parse("192.168.5.31"),5018),options =>
        {
            options.UseHttps(pfxPath, pfxPassword);
        });
    }
    else
    {
        Console.WriteLine("⚠️ 证书未找到,使用开发证书(浏览器可能仍报错)");
        serverOptions.ListenAnyIP(5001, options =>
        {
            options.UseHttps(); // 使用 ASP.NET Core 开发证书
        });
}
});

配置文件配置

{
  "Kestrel": {
    "Certificates": {
      "Default": {
        "Path": "certs/server.pfx",
        "Password": "yourpassword123"
      }
    },
    "Endpoints": {
      "Https": {
        "Url": "https://192.168.5.31:5018",
        "Certificate": {
          "Path": "certs/server.pfx",
          "Password": "yourpassword123"
        }
      },
      "Http": {
        "Url": "http://192.168.5.31:5000"
      }
    }
  }
}

java启动设置证书

java 支持 .p12 格式(比 .jks 更现代),推荐使用。

openssl pkcs12 -export \
  -out server.p12 \
  -inkey 192.168.5.31-key.pem \
  -in 192.168.5.31.pem \
  -name "tomcat" \
  -password pass:changeit

将 server.p12 放入 Java 项目

your-spring-boot-app/
├── src/
│ └── main/
│ ├── resources/
│ │ └── server.p12 ← 放这里
│ └── java/
│ └── com/example/demo/DemoApplication.java
├── application.yml

配置 application.yml(Spring Boot)

server:
  port: 8443
  ssl:
    enabled: true
    key-store-type: PKCS12
    key-store: classpath:server.p12
    key-store-password: changeit
    key-alias: tomcat
    # client-auth: want/need(双向认证可选)

启动 Spring Boot 应用

mvn spring-boot:run
\# 或
java -jar your-app.jar