-
-
Save RodrigoLGuimaraes/fcc71baa86122c8f62d895b1917d9c4c to your computer and use it in GitHub Desktop.
// 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 | |
} | |
} |
Thanks for posting this code. I'm not clear with one thing, though. I have a pair of public-keys for my domain, and I do not have a clue about how to provide them to the allPublicKeys variable...
I'd appreciate some help with it.
Hello @jeetdholakia, thank you for you interest. The method ServerTrustPolicy.publicKeys() searches for all the certificates it can find on your app’s bundle and extracts the public keys from them, so if you want to use this code you have the option of exporting the ssl certificate of your domain and including it on your bundle. If you want to use the public key directly, you should replace that method call with and array of SecKey, where each SecKey object represents a public key.
Thanks for the response, Rodrigo.
I followed the first method that you mentioned and it works according to expectation. For public key pinning though, I found Trustkit being a better-suited option. It was easier to setup.
Thanks for the observation @jeetdholakia, I will look into TrustKit.
Do you want to know more about this code? Read the medium post:
https://medium.com/@devRodrigoLG/ssl-pinning-with-moya-in-swift-d5a5edae22c2?sk=4d95a4f973a51124d89e2fe5e0d7b864