iOS (기능)
[SWIFT] Https 인증서 관련 우회 방법(Webview, API(Http통신/Alamofire)
겸손할 겸
2021. 7. 30. 13:19
[개요]
웹뷰를 통해 Https로 된 페이지, 도메인을 열 때 해당 인증서가 사설 인증서라면 웹뷰에서 경고를 날린다. 이는 웹뷰 로드 뿐 아니라, URLSession이나 Http통신 라이브러리인 Alamofire도 동일하다.
이때, 특정 Host값을 비교하여 해당 Host일 경우 인증서를 체크하지 않고 통과하도록 한다.
[웹뷰]
단순한 페이지 이동을 할때 WKWebview사용 시, WKNavigationDelegate를 상속받았다면 아래와 같은 함수로 처리 가능하다.
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("[Gyeom] Https Host : \(challenge.protectionSpace.host)")
if challenge.protectionSpace.host.contains("g-y-e-o-m"){
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}else{
completionHandler(.performDefaultHandling, nil)
}
}
print를 통해 확인해보고, 통과해야할 경우 if문 처럼 사용할 것
[URLSession]
URLSession을 통해 Http통신을 할경우(API 통신 등), 그리고 URLSessionDelegate를 상속받았다면 아래와 같은 함수로 처리 가능하다.
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.host.contains("g-y-e-o-m"){
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}else{
completionHandler(.performDefaultHandling, nil)
}
}
[Alamofire]
만약 통신관련 함수를 URLSession이 아닌 Alamofire를 사용하여 하고 있다면 아래와 같이 처리 가능하다.
let delegate: Alamofire.SessionDelegate = alamofire.delegate
delegate.taskDidReceiveChallengeWithCompletion = {
(session, task, challenge, completionHandler) in
print("[Gyeom] taskDidReceiveChallengeWithCompletion : \(challenge.protectionSpace.host)")
if challenge.protectionSpace.host.contains("g-y-e-o-m"){
print("[Gyeom] Go pass")
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}else{
completionHandler(.performDefaultHandling, nil)
}
}