JavaFX WebView shows blank page when the web site ssl certificate is not trusted ( or self-signed)








JavaFX WebView shows blank page when the web site ssl certificate is not trusted (or self-signed). There is not errors/exceptions that you can see unless you set up a listener before you load the web site in WebView: The following code will show the error:
    WebView web = new WebView();
    web.getEngine().load("https://www.your-org.org");
    web.getEngine().getLoadWorker().stateProperty()
            .addListener((ov, oldState, newState) -> {
                System.err.println(web.getEngine().getLoadWorker()
                         .exceptionProperty());
            });
The error is like below:
java.lang.Throwable: SSL handshake failed
To resolve the error, if you trust the web site, you can ignore the error by adding following code before you start the WebView:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { 
    new X509TrustManager() {     
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            return null;
        } 
        public void checkClientTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
            } 
        public void checkServerTrusted( 
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    } 
}; 

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL"); 
    sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}

WebView web = new WebView();
web.getEngine().load("https://www.your-org.org");
NOTE: After executing the above code, your application will trust all https web sites. To have a more secure solution, you may maintain a local key store to add the trusted certificates, see this for more detail.

See also




No comments:

Post a Comment