2010-11-01 2 views
28

У меня есть два веб-приложения на основе Spring A и B на двух разных машинах.Отключение проверки сертификата SSL весной RestTemplate

Я хочу сделать https-вызов из веб-приложения A в веб-приложение B, однако я использую самозаверяющий сертификат в машине B. Так что мой запрос HTTPS завершается с ошибкой.

Как отключить проверку сертификата https при использовании RestTemplate весной? Я хочу, чтобы отключить проверку, потому что как веб-приложение А и B находятся в пределах внутренней сети, но передача данных должно происходить через HTTPS

ответ

26

Что вам нужно добавить обычай HostnameVerifier класс обходит проверку сертификата и возвращает значение ИСТИНА

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

Это необходимо разместить соответствующим образом в коде.

+0

Я использую SpringTemplate класса Spring, знаете ли вы, как я мог это сделать в RestTemplate? – Ram

+6

Фактически это находится за пределами RestTemplate. Некоторые примеры кода доступны по адресу http://forum.springsource.org/showthread.php?t=60854. Также смотрите http://stackoverflow.com/questions/1725863/ssl-handshake-issue-using-spring-resttemplate – Raghuram

+0

Пила эти ссылки и заработала. Спасибо :) – Ram

6
Add my response with 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; 
      } 
     } 
+0

NullHostnameVerifier verifier = new NullHostnameVerifier(); вы можете видеть, помните, что cookie - это String –

19
@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; 
} 
+0

charm .......... – Valath

9

По сути две вещи, которые вы должны сделать это использовать пользовательские TrustStrategy, который доверяет все сертификаты, а также использовать 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; 
} 
+1

спасибо, это сработало для меня! – Humoyun

+1

TrustStrategy acceptingTrustStrategy = (X509Certificate [] x509Certificates, String s) -> true; – Humoyun

+1

Спасибо, это спасло мою жизнь. Все остальные методы (добавление экспортированных .crt в java cacerts с использованием keytool, http://blog.codeleak.pl/2016/02/skip-ssl-certificate-verification-in.html и около 5 ~ 6 других сообщений stackoverflow, включая ответы на этом) провалился, занял 7 часов моего времени. Этот ответ был моей последней надеждой, спасибо. –

0

Вы можете использовать это с API HTTPClient.

public RestTemplate getRestTemplateBypassingHostNameVerifcation() { 
    CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); 
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); 
    requestFactory.setHttpClient(httpClient); 
    return new RestTemplate(requestFactory); 

} 
Смежные вопросы