[Development Details] The SpringBoot project changes the interface from HTTP to HTTPS

Certificate preparation

First, you need to generate an SSL certificate. You can use the OpenSSL tool or your own CA issuing authority to generate the certificate . I won't go into details here. If it is a testing phase, you can also use self-signed certificate .
Directly use jdk's keytool to generate it . The specific operation method is as follows:

  1. Run command prompt as administrator
  2. Use the command to enter the bin folder of the jdk installation path
  3. Then use the command: keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 to generate the key.

The above steps are shown in the figure below:
Insert image description here
Insert image description here
The generated certificate is as follows:
Insert image description here
paste it into the classpath of the project to use it.

Project configuration

Move the certificate file here:
Insert image description here
Then make some configurations in application.yml:
Be careful key-store-passwordnot to overwrite key-passwordit.

server:
  ssl:
    enabled: true #启用SSL
    key-store: classpath:keystore.p12 #文件位置
    key-store-password: root123 #密钥存储密码(即生成时要求输入两遍的那个的密钥库口令)
    key-store-type: PKCS12 #密钥存储类型

Restart the project. If the startup is successful, the configuration is successful.
Visit the original swagger interface of the project to test it.
Insert image description here
The above description appears correct.
Add the prefix in front and https://try again, the following interface may appear:
Insert image description here
Since the access is HTTPS, the browser will perform SSL verification. If the server is not configured with a legal SSL certificate, the browser will give a security warning. If it is just for testing, you can trust your own SSL certificate first, for example, add the certificate to the Trusted Root Certification Authorities in Chrome. In a production environment, you need to purchase a legal SSL certificate.
Here we are doing a personal test, so click on the details to access directly.
Insert image description here
Successfully entered the swagger interface:
Insert image description here
Test the interface and found that HTTPS has been successfully put in:
Insert image description here

How to do the front end?

The front-end access to the interface on HTTPS is similar to the interface on HTTP. You only need to change http in the URL to https. For example, if the original access is http://localhost:8080/api/user, change it to https://localhost:8080/api/user.

There is an issue to note here : the default port of HTTP is 80, while the default port of HTTPS is 443. It is recommended to specify the port to avoid mistakes.

Guess you like

Origin blog.csdn.net/qq_44778023/article/details/131307371