In this tutorial, we will be using a self-signed certificate for our spring boot application so that we can access it using HTTPS.
We will not cover the topic of SSL and why do we need it in this tutorial.
Generate p12 file
To use SSL we need to generate a P12 file and the command to generate it is:
keytool -genkeypair -alias demo -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore demo.p12 -validity 3650
After running the generate command you can see the output one by one:
PS C:\Users\yubaraj> keytool -genkeypair -alias demo -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore demo.p12 -validity 3650
Enter keystore password:
Re-enter new password:
What is your first and last name?
What is the name of your organizational unit?
What is the name of your organization?
What is the name of your City or Locality?
What is the name of your State or Province?
What is the two-letter country code for this unit?
Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
We should set a password with a minimum length of 6 and others can be left as default.
When finishes the above step it should generate a file with name demo.p12.
Let’s copy this file to our Spring Boot project directory. (I would prefer to save inside classpath. i.e. resources folder):
Now, you have to update your application.yml file like following:
# This is the password you entered during demo.p12 file generation
Let’s start our spring boot application and try to access it with localhost:8080 it should display messages like:
This is because we need to access our API with HTTPS.
Hence, try to browse https://localhost:8080 and you may see an error:
This is because we are using a self-signed certificate to secure our API call and that certificate is not trusted by our browser.
Let’s click on the Advanced button and click Continue to localhost (unsafe) link.
It should work.
Note: If your configuration does not work then the complete example can be found in this link https://github.com/yubarajkalathoki/blog-examples/tree/main/example-1.