Disabling SSL Certificate Validation in Spring RestTemplate

后端 未结 12 1473
花落未央
花落未央 2020-11-28 20:05

I am having two Spring based web apps A and B, on two different machines.

I want to make a https call from web app A to web app B, however I am using a self-signed c

12条回答
  •  日久生厌
    2020-11-28 20:22

    To overrule the default strategy you can create a simple method in the class where you are wired your restTemplate:

     protected void acceptEveryCertificate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        };
    
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(
                HttpClientBuilder
                        .create()
                        .setSSLContext(SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build())
                        .build()));
    }
    

    Note: Surely you need to handle exceptions since this method only throws them further!

提交回复
热议问题