如何在Spring Boot应用程序上启用HTTPS?

HTTPS是HTTP的安全版本,旨在提供传输层安全性(TLS)[安全套接字层(SSL)的后继产品],这是地址栏中的挂锁图标,用于在Web服务器和浏览器之间建立加密连接。HTTPS加密每个数据包以安全方式进行传输,并保护敏感数据免受窃听者或黑客的攻击。

自签名证书

其实可以使用位于JDK bin文件夹下的Keytool生成证书。

例如,C:\ Program Files \ Java \ jdk1.8.0_161 \ bin。可以使用两个自签名证书,如下所示。

  1. 通过自己的Java应用程序可以轻松访问JKS(Java密钥库)。JKS仅限于Java,不能从Java外部访问。
  2. PKCS12:另一方面,公钥加密标准是一种与语言无关的方法,用于存储加密的私钥和证书,并且存储时间已经足够长,基本上所有的地方都能支持。

如何生成 自签名证书

在Windows的搜索字段中键入cmd以找到命令提示符,然后以“以管理员身份运行”右键单击。使用如下的keytool命令。您可以提及所需的证书名称,如下所示。

C:\ Program Files \ Java \ jdk1.8.0_161 \ bin>

keytool -genkeypair -alias selfsigned_localhost_sslserver -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore ebininfosoft-ssl-key.p12 -validity 3650

自签名证书受密码保护。输入密码和其他详细信息,如以下屏幕截图所示。

如何在Spring Boot应用程序上启用HTTPS?

完成上述步骤后,便会创建PKS密钥并将其存储在JDK Bin文件夹下。

将SSL应用于Spring Boot应用程序

  1. 从JDK bin文件夹复制ebininfosoft-ssl-key并将其放在Spring Boot Application的src / main / resources下。
  2. 如下所示,将SSL密钥信息添加到application.properties中。
#SSL Key Info
security.require-ssl=true
server.ssl.key-store-password=India@123
server.ssl.key-store=src/main/resources/ebininfosoft-ssl-key.p12
server.ssl.key-store-type=PKCS12

POM文件

以下是我用来指定Spring Boot依赖项的POM.xml。

<dependencies>
2
<dependency>
3
<groupId>org.springframework.boot</groupId>
4
<artifactId>spring-boot-starter-web</artifactId>
5
</dependency>
6
<dependency>
7
<groupId>org.springframework.boot</groupId>
8
<artifactId>spring-boot-starter-data-jpa</artifactId>
9

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

控制器

用于演示HTTPS Get请求的简单HomeController供您参考。

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/home")
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String hello() {
return "welcome to spring boot application";
}
}

如果在不使用HTTPS的情况下访问Rest Endpoint(http:// localhost:8080 / home /),则会在浏览器中收到以下消息。

"Bad Request" (翻译:“错误的请求”)

主机和端口的这种组合则需要TLS。

如果使用HTTPS(https:// localhost:8080 / home /)来访问URL ,则会得到如下响应。

"Welcome to Spring Boot application."(翻译:“欢迎使用Spring Boot应用程序。”)

您可能还会对下面的文章感兴趣: