웹 개발

[java Spring] RestTemplate SSL ignore

노루아부지 2022. 1. 26. 15:56

Spring에는 RestAPI 호출을 도와줄 RestTemplate를 제공합니다.

이 때 HTTP가 아닌 HTTPS를 호출하면 아래와 같은 오류가 발생하는 경우가 있습니다.

  • java.security.cert.CertificateException: No name matching localhost found
  • unable to find valid certification path to requested target

 

이 오류들은 사설인증서를 사용할 경우, 신뢰하는 인증서목록에 등록되어 있지 않을 경우, 그리고 기타 인증서에 문제가 있을 경우 발생하는 오류입니다.

 

해결방법은 인증서를 추가하거나, 모든 인증서를 신뢰하는 방법이 있는데 이 글에서는 모든 인증서를 신뢰하는 방법에 대해 알아보고자 합니다.

 

1. 먼저, RestTemplate를 리턴하는 함수를 만듭니다.

/**
 * Rest API 통신 시, ssl 무시
 * @param ignoreSsl
 * @return
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static RestTemplate makeRestTemplate(boolean ignoreSsl) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
  if(ignoreSsl) {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> 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);
    requestFactory.setConnectTimeout(3 * 1000);
    requestFactory.setReadTimeout(3 * 1000);
    
    return new RestTemplate(requestFactory);
  }
  else {
    return new RestTemplate();
  }
}

 

2. 아래와 같이 사용할 수 있습니다.

public static boolean remove(String url, String id) {
  try {
    RestTemplate rest = makeRestTemplate(true);

    URI uri = URI.create(url + "/" + id);
    HttpHeaders headers = new HttpHeaders();
    HttpEntity entity = new HttpEntity(headers);

    ResponseEntity<String> res = rest.exchange(uri, HttpMethod.DELETE, entity, String.class);
    log.info("status:"+res.getStatusCodeValue());

    return res.getStatusCodeValue() == 200;
  }
  catch(Exception e) {
    log.error("API 호출 실패:" + e.getMessage(), e);
    return false;
  }
}

 

 

 

 

[참고사이트]

https://reference-m1.tistory.com/374

 

[Back end] RestTemplate SSL ignore (PKIX path building failed)

RestTemplate를 사용하여 API를 요청할 때 종종 볼 수 있는 오류이다. 인증서와 관련된 오류로써, API를 요청하는 Java의 신뢰하는 인증서 목록(keystore)에 사용하고자 하는 인증기관이 등록되어 있지 않

reference-m1.tistory.com

 

728x90
loading