Skip to content

Commit

Permalink
Added property to enable/disable invalid certificates
Browse files Browse the repository at this point in the history
  • Loading branch information
buzunboy committed Jul 19, 2021
1 parent 6c93a33 commit a91387f
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Sources/UsefulNetworkLayer/NetworkLayer/NetworkLayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ public class NetworkLayer: NSObject, URLSessionDataDelegate {
/// `URLSession` manager for the `NetworkLayer`.
public var _urlSession: URLSession!

/// If `true`, Network Layer will accept challenges, otherwise it will cancel authentication challenges.
///
/// Defaults to `true`.
public var allowInvalidCertificates: Bool = true

/// Private initializer
private override init() {
self.mainQueue = OperationQueue()
Expand Down Expand Up @@ -334,4 +339,31 @@ public class NetworkLayer: NSObject, URLSessionDataDelegate {
case error(code: Int, name: String)
}

public func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
checkChallenge(challenge, completionHandler: completionHandler)
}

public func urlSession(_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
checkChallenge(challenge, completionHandler: completionHandler)
}

private func checkChallenge(_ challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
var disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
var credentials: URLCredential? = nil
if allowInvalidCertificates {
if let trust = challenge.protectionSpace.serverTrust {
credentials = URLCredential(trust: trust)
}
} else {
disposition = .cancelAuthenticationChallenge
}
completionHandler(disposition, credentials)
}

}

0 comments on commit a91387f

Please sign in to comment.