代码之家  ›  专栏  ›  技术社区  ›  Prabhu R

在springrestemplate中禁用SSL证书验证

  •  50
  • Prabhu R  · 技术社区  · 14 年前

    我想从web应用程序a到web应用程序B进行一个https调用,但是我正在计算机B中使用自签名证书。因此,我的https请求失败。

    在Spring中使用restemplate时,如何禁用https证书验证?我想禁用验证,因为web应用A和B都在内部网络中,但必须通过HTTPS进行数据传输

    5 回复  |  直到 12 年前
        1
  •  30
  •   Raghuram    14 年前

    您需要添加的是自定义 HostnameVerifier 类绕过证书验证并返回true

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
    

    这需要适当地放在代码中。

        2
  •  47
  •   Raibaz Tej4493    7 年前
    @Bean
    public RestTemplate restTemplate() 
                    throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                        .loadTrustMaterial(null, acceptingTrustStrategy)
                        .build();
    
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    
        CloseableHttpClient httpClient = HttpClients.custom()
                        .setSSLSocketFactory(csf)
                        .build();
    
        HttpComponentsClientHttpRequestFactory requestFactory =
                        new HttpComponentsClientHttpRequestFactory();
    
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
     }
    
        3
  •  31
  •   rouble    7 年前

    信任所有证书的自定义信任策略 ,也可以使用 NoopHostnameVerifier()

    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.SSLContext;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
    import org.springframework.web.client.RestTemplate;
    
    public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        };
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }
    
        4
  •  7
  •   Renats Stozkovs Shah Tahir    4 年前

    用cookie添加我的响应:

    public static void main(String[] args) {
         MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
         params.add("username", testUser);
         params.add("password", testPass);
         NullHostnameVerifier verifier = new NullHostnameVerifier(); 
         MySimpleClientHttpRequestFactory requestFactory = new MySimpleClientHttpRequestFactory(verifier , rememberMeCookie);
         ResponseEntity<String> response = restTemplate.postForEntity(appUrl + "/login", params, String.class);
    
         HttpHeaders headers = response.getHeaders();
         String cookieResponse = headers.getFirst("Set-Cookie");
         String[] cookieParts = cookieResponse.split(";");
         rememberMeCookie = cookieParts[0];
         cookie.setCookie(rememberMeCookie);
    
         requestFactory = new  MySimpleClientHttpRequestFactory(verifier,cookie.getCookie());
              restTemplate.setRequestFactory(requestFactory);
    }
    
    
    public class MySimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
    
            private final HostnameVerifier verifier;
            private final String cookie;
    
            public MySimpleClientHttpRequestFactory(HostnameVerifier verifier ,String cookie) {
                this.verifier = verifier;
                this.cookie = cookie;
            }
    
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                if (connection instanceof HttpsURLConnection) {
                    ((HttpsURLConnection) connection).setHostnameVerifier(verifier);
                    ((HttpsURLConnection) connection).setSSLSocketFactory(trustSelfSignedSSL().getSocketFactory());
                    ((HttpsURLConnection) connection).setAllowUserInteraction(true);
                    String rememberMeCookie = cookie == null ? "" : cookie; 
                    ((HttpsURLConnection) connection).setRequestProperty("Cookie", rememberMeCookie);
                }
                super.prepareConnection(connection, httpMethod);
            }
    
            public SSLContext trustSelfSignedSSL() {
                try {
                    SSLContext ctx = SSLContext.getInstance("TLS");
                    X509TrustManager tm = new X509TrustManager() {
    
                        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                        }
    
                        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                        }
    
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                    };
                    ctx.init(null, new TrustManager[] { tm }, null);
                    SSLContext.setDefault(ctx);
                    return ctx;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return null;
            }
    
        }
    
    
        public class NullHostnameVerifier implements HostnameVerifier {
               public boolean verify(String hostname, SSLSession session) {
                  return true;
               }
            }
    
        5
  •  4
  •   Amit Parashar    7 年前

    您可以将其与HTTPClient API一起使用。

    public RestTemplate getRestTemplateBypassingHostNameVerifcation() {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        return new RestTemplate(requestFactory);
    
    }
    
        6
  •  0
  •   Yash Jagdale    5 年前

    我找到了一个简单的方法

        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
    
        RestTemplate restTemplate = new RestTemplate(requestFactory);
    
        7
  •  0
  •   sagaris    5 年前

     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()));
    }
    

    注意:您当然需要处理异常,因为这个方法只会进一步抛出异常!

        8
  •  0
  •   Sats    5 年前

    安全性:禁用https/TLS证书主机名检查,以下代码适用于spring boot rest模板

    *HttpsURLConnection.setDefaultHostnameVerifier(
            //SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
            // * @deprecated (4.4) Use {@link org.apache.http.conn.ssl.NoopHostnameVerifier}
            new NoopHostnameVerifier()
    );*
    
        9
  •  0
  •   user1986251    4 年前

    禁用SSL主机名验证程序的完整代码,

    RestTemplate restTemplate = new RestTemplate();
    //to disable ssl hostname verifier
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {
       @Override
        protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setHostnameVerifier(new NoopHostnameVerifier());
            }
            super.prepareConnection(connection, httpMethod);
        }
    });