티스토리 뷰

 

 

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

해결방법

  1. 모든 인증서 신뢰하기
  2. 인증서 추가 (keytool)

이번에 알아볼 방법은 1번에 해당하는 모든 인증서를 신뢰하는 방법이다. 이 방법은 조금은 위험한 방법이긴 하다. 하지만 대부분 이런 오류는 Local 환경에서 외부 API를 테스트하면서 개발할 때 주로 발생한다. Local 환경에서만 모든 인증서 신뢰하기를 적용하면 된다.

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

/**
 * @author reference-m1
 * @desc HttpClientConfig
 */
public class HttpClientConfig {

	/**
	 * restTemplate SSL ignore
	 * @return HttpComponentsClientHttpRequestFactory
	 * @throws KeyStoreException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static HttpComponentsClientHttpRequestFactory trustRequestFactory() 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);
        
        return requestFactory;
    }
}

 

 

application-local.yml

rest:
  ignore_ssl : true

 

Service



@Value("${rest.ignore_ssl}")
private Boolean IGNORE_SSL;

...



ResponseEntity<String> response = null;
if (IGNORE_SSL) {
	response = new RestTemplate(HttpClientConfig.trustRequestFactory()).postForEntity(url, request, String.class);
} else {
	response = new RestTemplate().postForEntity(url, request, String.class);
}

...

yml 파일을 이용하면 환경 별 설정을 통해 개발이 용이해진다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함