Skip to content

Instantly share code, notes, and snippets.

@RodrigoLGuimaraes
Last active February 1, 2022 08:07
Show Gist options
  • Save RodrigoLGuimaraes/fcc71baa86122c8f62d895b1917d9c4c to your computer and use it in GitHub Desktop.
Save RodrigoLGuimaraes/fcc71baa86122c8f62d895b1917d9c4c to your computer and use it in GitHub Desktop.
Creation of a Moya provider with SSL pinning
// 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
}
}
@RodrigoLGuimaraes
Copy link
Author

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