Skip to content

Instantly share code, notes, and snippets.

@Gordenstein
Last active November 11, 2023 11:07
Show Gist options
  • Save Gordenstein/123e9af133ea24050211fb42b5b5d031 to your computer and use it in GitHub Desktop.
Save Gordenstein/123e9af133ea24050211fb42b5b5d031 to your computer and use it in GitHub Desktop.
//
// SSLPinningDemo.swift
// SSLPinning
//
// Created by Eugene Gordenstein on 11/04/2023.
//
import Foundation
struct DemoNetworkClient {
let sessionDelegate: SessionDelegate
let session: URLSession
init() {
sessionDelegate = SessionDelegate()
session = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: nil)
}
func demoURLRequest() {
Task {
do {
let url = "https://stackoverflow.com"
let data = try await makeURLRequest(urlString: url)
print("Received data: \(data)")
} catch {
print("Error: \(error)")
}
}
}
private func makeURLRequest(urlString: String) async throws -> Data {
guard let url = URL(string: urlString) else {
throw URLError(.badURL)
}
let request = URLRequest(url: url)
let (data, _) = try await session.data(for: request)
return data
}
}
class SessionDelegate: NSObject {
let sslPinningManager: SSLPinningManager
override init() {
sslPinningManager = SSLPinningManager(pinnedKeyHashes: [
"jQJTbIh0grw0/1TkHSumWb+Fs0Ggogr621gT3PvPKG0=" // Valid until 15 Sep 2025
])
}
}
extension SessionDelegate: URLSessionTaskDelegate {
func urlSession(_: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
sslPinningManager.validate(challenge: challenge, completionHandler: completionHandler)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment