'Trust a Certificate Authority in Java

I'm trying to consume some webservices in my Spring boot Applications, I got this error in swagger when I try to execute my request, I tried to search for the url of the webservices in a browser (https://ip:port) then I got a security error telling me that the certificate authority is not recognized "SEC_ERROR_UNKOWN_ISSUER".. I thought that the problem is coming from there. I tried to export the certificate from the browser and to import it in my cacerts but it didn't work.. Could a problem in my code be the cause of this error?

{
  "timestamp": "2021-11-16T08:11:16.189+00:00",
  "status": 400,
  "error": "Bad Request",
  "message": "I/O error: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target",
  "path": "***"
}


Solution 1:[1]

Okay, I might be late with the answer but I am anyways going to post it here because I am pretty sure someone will need it in the future.

After hours of searching for the answer I found the reason. I haven't imported self-signed root CA certificate into the java's cacerts keystore and therefore, I kept on getting the same exception.

Command to add root CA to the cacerts keystore from one of the stackoverflow answers.

keytool -import -alias mycert -keystore  "<<your-JAVA_HOME-directory>>\jre\lib\security\cacerts" -file mycert.cer

However, it did not work for me and I had to point it to keytool -import -alias mycert -keystore "<<your-JAVA_HOME-directory>>\lib\security\cacerts" -file mycert.cer to my jdk instead of jre folder.

Default password of the keystore is "changeit"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akmal