Last active
June 26, 2020 09:24
-
-
Save cdongieux/9acbccc6eaebc2cb3198c263273a53d4 to your computer and use it in GitHub Desktop.
WebViewClient implementation for Android API 19 (maybe 21?) devices having issues with SSL certificates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Typical error: | |
* | |
* X509Util: Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. | |
* MyWebViewClient: onReceivedSslError: handler = [Handler (com.android.webview.chromium.WebViewContentsClientAdapter$3) {9d87c030}], error = [primary error: 3 certificate: Issued to: | |
* CN=*.bootstrapcdn.com,OU=Domain Control Validated; | |
* Issued by: CN=Sectigo RSA Domain Validation Secure Server CA,O=Sectigo Limited,L=Salford,ST=Greater Manchester,C=GB; | |
* on URL: https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css] | |
*/ | |
public class MyWebViewClient extends WebViewClient { | |
@Override | |
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { | |
Timber.d("onReceivedSslError called with: error = [%s]", error); | |
// Impl from: https://stackoverflow.com/a/37851959/1954497 | |
CertificateFactory cf; | |
try { | |
cf = CertificateFactory.getInstance("X.509"); | |
} catch (CertificateException e) { | |
e.printStackTrace(); | |
handler.cancel(); | |
return; | |
} | |
SslCertificate errorSslCertificate = error.getCertificate(); | |
Certificate errorX509Cert = getX509Certificate(cf, errorSslCertificate); | |
if (errorX509Cert != null) { | |
int[] embeddedCasResId = {R.raw.ca1, R.raw.ca2}; | |
boolean verified = false; | |
for (int embeddedCaResId : embeddedCasResId) { | |
if (verifyWithEmbeddedCertificate(view.getContext(), cf, errorX509Cert, embeddedCaResId)) { | |
verified = true; | |
break; | |
} | |
} | |
if (verified) { | |
handler.proceed(); | |
} else { | |
handler.cancel(); | |
} | |
} else { | |
handler.cancel(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment