SSL Certificate
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.
WebClientException PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetThis 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.
How to Fix It
There are several ways you can fix an issue-
by adding server certificate to Java trust store
Bypass SSL Validation (For Testing Only)
Use a Custom TrustStore and use it with webclient
1. Adding certificate to java truststore
Export the certificate from the website:
Import it into Java's truststore:
here the changeit is the default password that we can need to change. This need to be done in every environment.
2. Bypass SSL Validation (For Testing Only)
In this approach we bypass the SSL validation, This to be done in a development or testing environment. Do not use this in production.
3. Use a Custom TrustStore [ Best for me ]
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
Step 2: Create a New Truststore
additionally, we can verify the generated certificate
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:
Update application.properties/yaml:
Create Custom TrustStore and configure
Additional Security Tips:
Store sensitive information like passwords in a secure vault (e.g., HashiCorp Vault, AWS Secrets Manager)
Regularly update certificates and truststore:
Add certificate rotation procedures to your deployment pipeline
Last updated