知識庫 / Spring / Spring Boot RSS 訂閱

使用自簽名證書在 Spring Boot 中使用 HTTPS

Security,Spring Boot
HongKong
4
01:36 PM · Dec 06 ,2025

1. 概述

在本教程中,我們將學習如何在 Spring Boot 中啓用 HTTPS。為此,我們還將生成自簽名證書,並配置一個簡單的應用程序。

對於 Spring Boot 項目的更多詳細信息,可以參考以下資源。

2. 生成自簽名證書

在開始之前,我們將創建一個自簽名證書。我們將使用以下兩種證書格式之一:

  • PKCS12:Public Key Cryptographic Standards 是一個密碼保護格式,可以包含多個證書和密鑰;它是一種在行業中廣泛使用的格式。
  • JKS:Java KeyStore 與 PKCS12 類似;它是一種專有格式,僅限於 Java 環境。

我們可以使用 keytool 或 OpenSSL 工具從命令行生成證書。 Keytool 隨 Java 運行時環境一起提供,而 OpenSSL 可以從 這裏 下載。

為了我們的演示,讓我們使用 keytool。

2.1. 生成密鑰存儲

現在我們將創建一個一組加密密鑰,並將它們存儲在密鑰存儲中。

我們可以使用以下命令生成我們的 PKCS12 密鑰存儲:

keytool -genkeypair -alias baeldung -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore baeldung.p12 -validity 3650

我們可以存儲任意數量的密鑰對,每個密鑰對都通過一個唯一的別名進行標識。

為了生成我們的 JKS 格式密鑰庫,可以使用以下命令:

keytool -genkeypair -alias baeldung -keyalg RSA -keysize 2048 -keystore baeldung.jks -validity 3650

我們建議使用 PKCS12 格式,這是一種行業標準格式。因此,如果我們已經擁有 JKS 密鑰庫,可以使用以下命令將其轉換為 PKCS12 格式:

keytool -importkeystore -srckeystore baeldung.jks -destkeystore baeldung.p12 -deststoretype pkcs12

我們需要提供源密鑰存儲密碼,並設置一個新的密鑰存儲密碼。密鑰別名和密鑰存儲密碼稍後會用到。

3. 在 Spring Boot 中啓用 HTTPS

Spring Boot 提供了一組聲明式的 `server.ssl.* 屬性。 我們將在本示例應用程序中使用這些屬性來配置 HTTPS。

我們從一個簡單的 Spring Boot 應用程序開始,該應用程序包含 Spring Security 和由“/welcome”端點處理的歡迎頁面。

然後,我們將之前步驟中生成的“baeldung.p12”文件複製到“src/main/resources/keystore”目錄中。

3.1. 配置 SSL 屬性

現在我們將配置與 SSL 相關的屬性:

# The format used for the keystore. It could be set to JKS in case it is a JKS file
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore/baeldung.p12
# The password used to generate the certificate
server.ssl.key-store-password=password
# The alias mapped to the certificate
server.ssl.key-alias=baeldung

由於我們正在使用啓用了 Spring Security 的應用程序,讓我們配置它僅接受 HTTPS 請求:

server.ssl.enabled=true

4. 調用 HTTPS URL現在我們已在應用程序中啓用 HTTPS,接下來讓我們探討如何使用自簽名證書調用 HTTPS 端點,並瞭解客户端如何操作。

首先,我們需要創建一個信任存儲。由於我們已生成了 PKCS12 文件,我們可以將其作為信任存儲使用。下面是定義信任存儲的詳細信息:

#trust store location
trust.store=classpath:keystore/baeldung.p12
#trust store password
trust.store.password=password

然後我們需要準備一個包含信任存儲的 SSLContext,並創建一個定製的 RestTemplate

RestTemplate restTemplate() throws Exception {
    SSLContext sslContext = new SSLContextBuilder()
      .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray())
      .build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
    HttpClient httpClient = HttpClients.custom()
      .setSSLSocketFactory(socketFactory)
      .build();
    HttpComponentsClientHttpRequestFactory factory = 
      new HttpComponentsClientHttpRequestFactory(httpClient);
    return new RestTemplate(factory);
}

為了演示目的,我們確保 Spring Security 允許所有傳入的請求:

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 
    http.authorizeRequests() 
      .antMatchers("/**") 
      .permitAll(); 
    return http.build(); 
}

最後,我們可以調用 HTTPS 端點:

@Test
public void whenGETanHTTPSResource_thenCorrectResponse() throws Exception {
    ResponseEntity<String> response = 
      restTemplate().getForEntity(WELCOME_URL, String.class, Collections.emptyMap());

    assertEquals("<h1>Welcome to Secured Site</h1>", response.getBody());
    assertEquals(HttpStatus.OK, response.getStatusCode());
}

5. 結論

在本文中,我們首先學習瞭如何生成自簽名證書,以便在 Spring Boot 應用程序中啓用 HTTPS。然後,我們討論瞭如何調用 HTTPS 啓用的端點。

最後,要運行代碼示例,需要取消註釋 pom.xml 中的以下 start-class 屬性:

<start-class>com.baeldung.ssl.HttpsEnabledApplication</start-class>
user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.