Last active
February 1, 2022 08:07
-
-
Save RodrigoLGuimaraes/fcc71baa86122c8f62d895b1917d9c4c to your computer and use it in GitHub Desktop.
Creation of a Moya provider with SSL pinning
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
// 1 - provider creation | |
let provider = MoyaProvider<MyRouter>( | |
manager: AlamofireSessionManagerBuilder().build() | |
) | |
// 2 - session manager builder | |
class AlamofireSessionManagerBuilder { | |
var policies: [String: ServerTrustPolicy]? | |
var configuration = URLSessionConfiguration.default | |
// 3 - builder initializer | |
init(includeSSLPinning: Bool = true) { | |
if includeSSLPinning { | |
let allPublicKeys = ServerTrustPolicy.pinPublicKeys( | |
publicKeys: ServerTrustPolicy.publicKeys(), | |
validateCertificateChain: true, | |
validateHost: true | |
) | |
self.policies = [ | |
"firstsubdomain.mycompany.com": allPublicKeys, | |
"secondsubdomain.mycompany.com": allPublicKeys | |
] | |
} | |
} | |
//4 - Example function that configures alamofire's session manager | |
//to increase timeout interval, useful for upload requests. | |
func prepareForFileUpload() -> Self { | |
configuration.timeoutIntervalForRequest = 300 | |
configuration.timeoutIntervalForResource = 300 | |
return self | |
} | |
// 5 - session manager creator | |
func build() -> Manager { | |
var serverTrustPolicyManager: ServerTrustPolicyManager? | |
if let policies = self.policies { serverTrustPolicyManager = ServerTrustPolicyManager(policies: policies) } | |
let manager = Manager(configuration: configuration, | |
serverTrustPolicyManager: serverTrustPolicyManager) | |
manager.startRequestsImmediately = false | |
return manager | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the observation @jeetdholakia, I will look into TrustKit.