Let’s say you want to invoke a REST API from your spring boot application.
And it is protected with SSL.
In other words you need an SSL certificate to access that application, else you won’t be given access to it.
Your java keystore already has a lot of inbuilt certificates(In my local it is present in C:\softwares\jdk-16\lib\security\cacerts). cacerts is the default keystore provided by java.
If the API you are going to consume uses one of those certificates you don’t have to do anything different to consume that API.
You can consume it the regular way using Spring REST template
Something like this:
RestTemplate restTemplate = new RestTemplate(); Map response = restTemplate.getForObject("https://example.com/api", Map.class);
where “https://example.com/api” is the api you want to consume.
But what if the certificate isn’t present in your default keystore?
You need to follow the below steps then:
STEP1: Download the certificates through browser.
All major browsers have access to the major SSL certificates and they allow you to download them.
You need to hit the domain URL of the REST API you want to consume in your browser.
This will show certificate menu. Click that and in the Certification Path you will see the certificates. The certificates will be in a hierarchy , the top one the root certificate , the next one the intermediate certificate and the rest are the leaf certificates.
You need the root certificate and the intermediate certificate in your java keystore to access the protected REST API.
Download both root certificate and the intermediate certificate by copying them to a file under Details tab.
STEP2: Import the certificate to your java keystore:
Go to bin folder of your java installation (if you have set java path globally then you can fire the command from any path)
Then fire the below command for each of the certificate you downloaded:
keytool -importcert -file root.cer
you can provide alias name for your certificate using -alias keyword as well.
For example I downloaded one of the certificates from my blog and imported it as below:
You will be asked for a password for the certificate. You need to enter it and then type “yes” when asked if the certificate can be trusted or not.
Now you can consume the REST API using Spring Rest Template the regular way.