1. Overview
1.概述
In this tutorial, we’ll learn how to enable HTTPS in Spring Boot. For this purpose, we’ll also generate a self-signed certificate, and configure a simple application.
在本教程中,我们将学习如何在Spring Boot中启用HTTPS。为此,我们还将生成一个自签名的证书,并配置一个简单的应用程序。
For more details on Spring Boot projects, we can refer to a bunch of resources here.
关于Spring Boot项目的更多细节,我们可以参考一堆资源这里。
2. Generating a Self-Signed Certificate
2.生成自签名证书
Before getting started, we’ll create a self-signed certificate. We’ll use either of the following certificate formats:
在开始之前,我们将创建一个自签名的证书。我们将使用下列证书格式中的一种。
- PKCS12: Public Key Cryptographic Standards is a password protected format that can contain multiple certificates and keys; it’s an industry-wide used format.
- JKS: Java KeyStore is similar to PKCS12; it’s a proprietary format and is limited to the Java environment.
We can use either keytool or OpenSSL tools to generate the certificates from the command line. Keytool is shipped with Java Runtime Environment, and OpenSSL can be downloaded from here.
我们可以使用keytool或OpenSSL工具从命令行生成证书。Keytool是随Java运行环境一起提供的,而OpenSSL可以从这里下载。
For our demonstration, let’s use keytool.
对于我们的演示,让我们使用keytool。
2.1. Generating a Keystore
2.1.生成一个密钥库
Now we’ll create a set of cryptographic keys, and store them in a keystore.
现在我们将创建一组加密密钥,并将其存储在一个密钥库中。
We can use the following command to generate our PKCS12 keystore format:
我们可以使用以下命令来生成我们的PKCS12密钥库格式。
keytool -genkeypair -alias baeldung -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore baeldung.p12 -validity 3650
We can store any number of key-pairs in the same keystore, with each identified by a unique alias.
我们可以在同一个钥匙库中存储任意数量的钥匙对,每个钥匙对由一个独特的别名来识别。
For generating our keystore in a JKS format, we can use the following command:
为了生成JKS格式的密钥库,我们可以使用以下命令。
keytool -genkeypair -alias baeldung -keyalg RSA -keysize 2048 -keystore baeldung.jks -validity 3650
We recommend using the PKCS12 format, which is an industry standard format. So in case we already have a JKS keystore, we can convert it to PKCS12 format using the following command:
我们建议使用PKCS12格式,它是一种行业标准格式。因此,如果我们已经有一个JKS密钥库,我们可以用下面的命令将其转换为PKCS12格式。
keytool -importkeystore -srckeystore baeldung.jks -destkeystore baeldung.p12 -deststoretype pkcs12
We’ll have to provide the source keystore password and also set a new keystore password. The alias and keystore password will be needed later.
我们必须提供源钥匙库密码,同时也要设置一个新的钥匙库密码。稍后将需要别名和keystore密码。
3. Enabling HTTPS in Spring Boot
3.在Spring Boot中启用HTTPS
Spring Boot provides a set of a declarative server.ssl.* properties. We’ll use those properties in our sample application to configure HTTPS.
Spring Boot提供了一套声明性的server.ssl.*属性。我们将在我们的示例应用程序中使用这些属性来配置HTTPS。
We’ll start from a simple Spring Boot application with Spring Security that contains a welcome page handled by the “/welcome” endpoint.
我们将从一个简单的Spring Boot应用程序与Spring Security开始,其中包含一个由”/welcome“端点处理的欢迎页面。
Then we’ll copy the file named “baeldung.p12,” generated in the previous step, into the “src/main/resources/keystore” directory.
然后我们将上一步生成的名为”baeldung.p12″的文件复制到”src/main/resources/keystore“目录。
3.1. Configuring SSL Properties
3.1.配置SSL属性
Now we’ll configure the SSL related properties:
现在我们将配置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
Since we’re using a Spring Security enabled application, let’s configure it to accept only HTTPS requests:
由于我们使用的是一个启用了Spring Security的应用程序,让我们把它配置为只接受HTTPS请求。
server.ssl.enabled=true
4. Invoking an HTTPS URL
4.调用一个HTTPS URL
Now that we have enabled HTTPS in our application, let’s move on to the client, and explore how to invoke an HTTPS endpoint with the self-signed certificate.
现在我们已经在我们的应用程序中启用了HTTPS,让我们转向客户端,探索如何用自签的证书调用HTTPS端点。
First, we need to create a trust store. As we have generated a PKCS12 file, we can use the same as the trust store. Let’s define new properties for the trust store details:
首先,我们需要创建一个信任存储。由于我们已经生成了一个PKCS12文件,我们可以使用同样的文件作为信任存储。让我们为信任存储的细节定义新的属性。
#trust store location
trust.store=classpath:keystore/baeldung.p12
#trust store password
trust.store.password=password
Then we need to prepare an SSLContext with the trust store and create a customized RestTemplate:
然后我们需要准备一个带有信任存储的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);
}
For the sake of the demo, let’s make sure Spring Security allows any incoming requests:
为了演示,让我们确保Spring Security 允许任何进入的请求。
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**")
.permitAll();
return http.build();
}
Finally, we can make a call to the HTTPS endpoint:
最后,我们可以对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. Conclusion
5.结论
In this article, we first learned how to generate a self-signed certificate to enable HTTPS in a Spring Boot application. Then we discussed how to invoke an HTTPS-enabled endpoint.
在这篇文章中,我们首先学习了如何在Spring Boot应用程序中生成一个自签名证书以启用HTTPS。然后,我们讨论了如何调用启用了HTTPS的端点。
As always, we can find the complete source code over on GitHub repository.
一如既往,我们可以在GitHub资源库上找到完整的源代码。
Finally, to run the code sample, we need to un-comment the following start-class property in the pom.xml:
最后,为了运行代码样本,我们需要取消对pom.xml中以下start-class属性的注释。
<start-class>com.baeldung.ssl.HttpsEnabledApplication</start-class>