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:
- Run command prompt as administrator
- Use the command to enter the bin folder of the jdk installation path
- 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:
The generated certificate is as follows:
paste it into the classpath of the project to use it.
Project configuration
Move the certificate file here:
Then make some configurations in application.yml:
Be careful key-store-password
not to overwrite key-password
it.
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.
The above description appears correct.
Add the prefix in front and https://
try again, the following interface may appear:
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.
Successfully entered the swagger interface:
Test the interface and found that HTTPS has been successfully put in:
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.