Search code examples
javaspringoauthjwtboot

Spring boot Jwt signed with RS256


I'm given a url - jwks_uri= https://xxxxx/oauth/nam/keys
... which produces this json:

{
     "keys": [{
             "kty": "RSA",
             "use": "sig",
             "alg": "RS256",
             "kid": "233921010515334582428573459295448396160651486998",
             "x5c": ["MIIFQjCCBCqgAwIBAgIUKPlhgf+gbz7h0arpJdYiOXxj5xYwDQYJKoZIhvcNAQELBQAwNTEaMBgGA1UECxMRT3JnYW5pemF0aW9uYWwgQ0ExFzAVBg..........wTBo45axM="],
             "x5t": "BBSLHq3rpiVLP2rota71boxAdqE",
             "x5tS256": "VAvMs-i58nz5UjOzyOEPpDubjgsNDK_m5z7w8dudPaw",
             "n": "okBvqleqjWLqLQ20cd9oajuOFZgOdPgD0rz6PddT1uW0iPkZ53Az68D_9s0fSMh996iGxN8sZFcCO-v0DXFBmUZb8D1VuBbx4v8Q_OUWhUk6V0QgUnzsdEYP39tZqU4gq KMuwzCbqqD1tj1C510tT8LK8lJjYuIjP-eNHv_WaL9QAH0iRwOWXA_a9ZwEoOhI0R-HqnvvJNyuUnh0umHDow3Uu7uuTKMFmziNzcB4ANBrKytVsfqBz2M9qNi6YqpT1ysGyX_M_PCja 2q8CDQxpcUm7XikFNdjutTR_B1gXDEk0Y8O7MgeKQcbYq1jMGEzIUabeka6jbBE2RR-mzV1YQ",
             "e": "AQAB"
         }
     ]
}

the company claims that I have everything needed to verify the public key of the jwt but in my code I keep getting the error

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

This is my method:

private RSAPublicKey loadPublicKey(DecodedJWT token) throws JwkException, MalformedURLException {
    
    final String url = "https://XXXXXXXX/oauth/nam/keys"; //getKeycloakCertificateUrl(token);
 //   final String url = "https://XXXXXXXXX/api/GetCA";



    JwkProvider provider = new UrlJwkProvider(new URL(url));

    return (RSAPublicKey) provider.get(token.getKeyId()).getPublicKey();
}

Solution

  • When your Java code tries to get the contents from that URL (the public key you need to verify JWTs) it can't establish a proper connection because it doesn't trust the certificate used by that page. It's the SSL certificate used by the page itself, not the public key that is returned at that endpoint. What you should do, is to obtain that certificate (you can open the https://XXXXXXXX/oauth/nam/keys page in a browser and download the certificate), then add it to your Java truststore. You will find detailed instructions on how to do it under this link posted by juanlumn: Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?