Skip to content

Instantly share code, notes, and snippets.

@jinal90
Created May 22, 2020 21:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jinal90/47917b772dae8f13f0533a084849ce28 to your computer and use it in GitHub Desktop.
Save jinal90/47917b772dae8f13f0533a084849ce28 to your computer and use it in GitHub Desktop.
Code snippet to explain a SSL pinning Alamofire and Server trust policy.
// 1. Basic configuration for creating Alamofire manager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = 60
var serverTrustPolicies: [String: ServerTrustPolicy] = [:]
// 2. Pass your certificate filename, type and directory path to load the cefrtificate
guard let certificatePath = Bundle.main.path(forResource: "CertificateFileName", ofType: "der", inDirectory: "assets/certificate") else{
print("OOPS! There is an error in certificate path")
}
let localCertificate: NSData = NSData(contentsOfFile: certificatePath)!
// 3. Set validateCertificateChain and validateHost to true for this certficate
let pinCertificate = ServerTrustPolicy.pinCertificates(
certificates: [SecCertificateCreateWithData(nil, localCertificate)!],
validateCertificateChain: true,
validateHost: true
)
// 4. Set the loaded certificate for your dns.
// If the app is intended to connect with multiple backends, then set certificates for each backend system similarly.
serverTrustPolicies["www.example.com"] = pinCertificate
// 5. Create Alamofire session manager and set the server trust policies that we just created.
let manager = Alamofire.SessionManager(configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
// 6. Finally connect with the backend and trigger the rest service call
guard let url = URL(string: "https://www.example.com/restservice") else {
print("Error in forming the URL")
}
// Desired parameters and headers
let parameters:Dictionary<String,String> = ["key1":"value1","key2":"value2"]
let headers = ["Content-Type": "application/json", "Accept": "application/json"]
manager.request(url, method: .get, parameters: parameters, headers: headers)
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
print("Error while fetching response \(response)")
return
}
print("Success response received: \(response.result.value)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment