1

I have created a Java WebSocket Jetty server who uses an API to retrieve some data using HttpUrlConnection(). I also have a MongoDb instance running in a docker container listening to port 27017. When running the server I create a connection with MongoDB and then try to retrieve some data with the API. Subsequently I get the following error:

javax.net.ssl.SSLHandshakeException:  sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Here's the weird part: without creating any connections to Mongo, the data retrieval runs smoothly with no errors or exceptions (the certificate exists). My guess is that maybe there is some conflict between the MongoDB driver and Http handler but I could not find anything online.

Here is the code for the API request:

            URL url=new URL(s);
            HttpURLConnection con  =(HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");

            br = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            while ((line = br.readLine()) != null) {
                jsonData += line + "\n";
            }
            JSONObject ob;

and here is the code to connect to the MongoDB:

public void connect() {

        try {
            client=new MongoClient("localhost:27017");
            db=client.getDatabase("QuoteDB");
            coll = db.getCollection("quotes");
        }catch(MongoException e) {
            System.out.println(e.getMessage());
        }

}

The exception is thrown in this line:

br = new BufferedReader(new InputStreamReader(con.getInputStream()));
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

0

PKIX path building failed... means that the connection is not finding the server root certificate in the local truststore

Java URLConnection uses the default truststore. If the connection to a SSL server fails after connecting to MongoDB, it means "somebody" has changed the truststore.

Look for System.setProperty("javax.net.ssl.trustStore") in your code and ensure System.getProperty("javax.net.ssl.trustStore") has the same value before invoking the external API when using MOngoDB as when not.

pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • Hi thanks for your reply, I have the _System.setProperty("javax.net.ssl.trustStore", "jssecacerts");_ in the invoked method the sends the API request. Also writting _System.getProperty("javax.net.ssl.trustStore")_ doesn't make a difference. Am I doing something wrong? – Captain_Rookie Nov 05 '17 at 11:47
  • You are pointing the default truststore to the local file "jssecacerts". Do you have that file or do you really want to point to the default truststore file of the JVM in `/lib/security/jssecacerts` ? Where did you import the root CA cert? – pedrofb Nov 05 '17 at 13:44