[TroubleShooting] URLSession에서 SSL 인증 예외 처리하기

Martin Kim·2022년 5월 12일
0

TroubleShooting

목록 보기
1/1

Raywenderlich 예제를 따라하던 중, NASA 공개 API 데이터를 다운로드하는 예제에서 다음과 같은 오류가 발생했다.

The certificate for this server is invalid. You might be connecting to a server that is pretending to be "eonet.sci.gsfc.nasa.gov" which could put your confidential information at risk.

결론적으로 말하면 저기 서버에 SSL인증서 문제가 있고, 아마 브라우저로 직접 api에 접속하면 다음과 같은 익숙한 이미지가 뜰 것이다.

보통 이런 경우 브라우저에서는 고급 -> 무시하고 그냥 접근 이런식으로 할텐데... 앱에서는 이렇게 처리할수 없다. 시뮬레이터에서는 어떻게 처리하는지 찾아보았다.

우선 Charles라는 프록시 툴을 사용하는 방법은 먹히지 않았다. 내가 사용법을 잘 몰랐을 수도 있는데, 인증서를 시뮬레이터에 설치했음에도 불구하고 계속 오류를 뱉어냈다.

그러던 중 URLSession의 delegate를 이용해 무시하는 방법을 찾아내었다.
아래 코드를 활용해 URLSessionDelegate 메서드를 구현하면 된다.

extension EONET: URLSessionDelegate { 
  func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    
    //accept all certs when testing, perform default handling otherwise
    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
  }
}

물론 요청하는 URLSession 객체는 흔히 사용하는 shared 객체가 아닌, 아래와 같은 코드로 생성해야 한다. 그래야 delegate로 해당 응답을 처리할 수 있게 된다.

...
URLSession(configuration: .ephemeral, 
			delegate: EONET(), delegateQueue: nil)
        	.rx.response(request: request)
.
.
.
profile
학생입니다

0개의 댓글