Created
October 12, 2018 12:34
-
-
Save NikolaiRuhe/d9395adda8249afee62e8da6e3be3868 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Request.swift | |
// TLS-Test | |
// | |
// Created by Nikolai Ruhe on 12.10.18. | |
// Copyright © 2018 Nikolai Ruhe. All rights reserved. | |
// | |
import Foundation | |
class Request { | |
static let host = "192.168.1.22" | |
static let port = 4433 | |
let session = URLSession(configuration: URLSessionConfiguration.default, | |
delegate: SessionDelegate(), | |
delegateQueue: nil) | |
var task: URLSessionTask? | |
func start() { | |
let url = URL(string: "https://\(Request.host):\(Request.port)/")! | |
task = session.dataTask(with: url, completionHandler: { | |
(data, response, error) in | |
if let error = error { | |
print("task did complete with error: \(error)") | |
} else if let response = response { | |
print("task did complete with response: \(response)") | |
if let string = String(bytes: data ?? Data(), encoding: .utf8) { | |
print("\(string)") | |
} | |
} else { | |
print("task did complete without response") | |
} | |
}) | |
print("will resume task") | |
task?.resume() | |
} | |
class SessionDelegate: NSObject {} | |
} | |
extension Request.SessionDelegate : URLSessionDelegate { | |
func trust(from protectionSpace: URLProtectionSpace) -> SecTrust? { | |
guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust else { | |
return nil | |
} | |
guard protectionSpace.host == Request.host else { | |
return nil | |
} | |
guard protectionSpace.protocol == "https" else { | |
return nil | |
} | |
guard let trust = protectionSpace.serverTrust else { | |
return nil | |
} | |
var result = SecTrustResultType.invalid | |
guard SecTrustEvaluate(trust, &result) == errSecSuccess else { | |
return nil | |
} | |
switch result { | |
case .unspecified: | |
// The OS trusts this certificate implicitly. | |
return nil | |
case .recoverableTrustFailure: | |
let certificateCount = SecTrustGetCertificateCount(trust) | |
print("certificates: [\(certificateCount)]") | |
return trust | |
default: | |
return nil | |
} | |
} | |
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { | |
guard let trust = trust(from: challenge.protectionSpace) else { | |
completionHandler(.performDefaultHandling, nil) | |
return | |
} | |
completionHandler(.useCredential, URLCredential(trust: trust)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment