Last active
November 11, 2023 11:07
-
-
Save Gordenstein/123e9af133ea24050211fb42b5b5d031 to your computer and use it in GitHub Desktop.
Demo source file for the Medium article - https://medium.com/lunasolutions/mastering-ssl-pinning-in-swift-no-third-party-libraries-required-42a377db80ff?source=friends_link&sk=b75e8720d528acfad013f0ec2f6901e6
This file contains 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
// | |
// 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