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 | |
} | |
} |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
https://developer.apple.com/documentation/security/seckey