Sometimes when we call an endpoint That has https And the https certificate is self signed its not signed by public certificate providers then we can get an error back java test store cannot be a certificate.
WebClientExceptionPKIX path building failed:sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This is a common problem when dealing with HTTPS endpoints that have self-signed certificates or certificates not in Java's trusted keystore.
Why This Exception Occurs
Untrusted SSL/TLS Certificate:
The server you're calling (the one causing the exception) is using an SSL/TLS certificate that is not trusted by the Java TrustStore.
This can happen if:
The certificate is self-signed (not issued by a trusted Certificate Authority).
The certificate is issued by a private or internal CA that is not included in the Java TrustStore.
The certificate is expired or invalid.
Java TrustStore:
Java uses a TrustStore (cacerts) to store trusted root certificates. If the server's certificate is not signed by a CA in this TrustStore, Java cannot validate it, and this exception is thrown.
Local Machine Testing:
When testing from your local machine, the server you're calling might be using a self-signed or internal certificate that is not trusted by default in the Java TrustStore.
In this approach, we first create a custom truststore then configure it in webclient calling that particular endpoint.
Here are the following steps involved -
Step 1: Export the Certificate from the Server
# Use openssl to export the certificateopenssls_client-connectsecure.website.com:443</dev/null|sed-ne'/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'>website_certificate.pem
Step 2: Create a New Truststore
# Create a new truststore and import the certificatekeytool-import-filewebsite_certificate.pem-aliascerfgs-keystorecustom_truststore.jks# You'll be prompted to:# 1. Create a secure password for the truststore# 2. Trust the certificate (type 'yes')
additionally, we can verify the generated certificate
# List certificates in your truststorekeytool-list-v-keystorecustom_truststore.jks
Step 3: Configure Spring Boot Application
Now we need to use this generated truststore in spring boot app and configure it for webclient.
Move the truststore file to your resources folder:
# copy the generated certificate and paste it in resources foldercpcustomer_trustsotore.jssrc/main/resources/security/custom_truststore.jks