Created
May 22, 2020 21:23
-
-
Save jinal90/47917b772dae8f13f0533a084849ce28 to your computer and use it in GitHub Desktop.
Code snippet to explain a SSL pinning Alamofire and Server trust policy.
This file contains 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. 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