SSL Certificate Verification : javax.net.ssl.SSLHandshakeException

后端 未结 3 1939
别那么骄傲
别那么骄傲 2020-12-29 00:13

I am trying to call a HTTPS REST API through Jersey Client. And on the course of development i stumble upon following error :

Exception in thread         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-29 00:54

    @jww rightly answers the question

    Is it OK to skip SSL verification? No. That's very irresponsible.

    However, in some cases you may not control the server in question to be able to install a valid certificate. If the server belongs to someone else, and you trust that server, a better solution is to use a "white list" to validate certificates only for trusted servers, otherwise use normal validation.

    public static class WhitelistHostnameVerifier implements HostnameVerifier {
        private static final HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
        private Set trustedHosts;
    
        public WhitelistHostnameVerifier(Set trustedHosts) {
            this.trustedHosts = trustedHosts;
        }
    
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (trustedHosts.contains(hostname)) {
                return true;
            } else {
                return defaultHostnameVerifier.verify(hostname, session);
            }
        }
    }
    

    And install it once:

    HttpsURLConnection.setDefaultHostnameVerifier(
        new WhitelistHostnameVerifier(Sets.newHashSet("trustedhost.mydomain.com")));
    

    If you're going to disable a security check, don't do it globally...

提交回复
热议问题