" Certificate Pinning"
We used Alamofire for making network calls. To implement SSL pinning, we have to use Alamofire Session Manager which is responsible for creating and managing request objects, as well as their underlying NSURLSession.
We have to initialize Alamofire session manager with ServerTrustPolicyManager - responsible for managing the mapping of ServerTrustPolicy objects to a given host. Now, what is ServerTrustPolicy?
The ServerTrustPolicy evaluates the server trust generally provided by an NSURLAuthenticationChallenge when connected to the server over the secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made.
Let's jump to the coding part:
For initializing Alamofire shared Session Manager, we need to provide it with URLSessionConfiguration. An URLSessionConfiguration defines the behaviour and policies to use when uploading and downloading data using an URLSession object. When uploading or downloading data, creating a configuration object is always the first step you must take.
We will be using the default session configuration.
We can add any additional headers in httpAdditionalHeaders property of URLSessionConfiguration.
The second object we need to build the Session manager is ServerTrustPolicyManager.
ServerTrustPolicyManager is responsible for managing the mapping of ServerTrustPolicy objects to a given host.
To build ServerTrustPolicyManager, we need to initialize it with a dictionary of type [String: ServerTrustPolicy].
To build this dictionary, we will use .pinCertificates case of enum ServerTrustPolicy.
For this, we need to provide it with an array of SecCertificate , which we will store in our application.
You can create your SSL certificate using given command in terminal.
openssl s_client -showcerts -servername YOURSERVERNAME -connect YOURSERVERNAME:443 < /dev/null | openssl x509 -outform DER > YOURCERTIFICATENAME.cer
This command will generate an SSL certificate with .cer extension in your current directory. After that, drag the created certificate into Xcode.
You can use a below-mentioned method to create an array of SecCertificate from certificates files saved in application.
Now, we can create the dictionary ([String : ServerTrustPolicy]) to built ServerTrustPolicyManager.
It’s time to build a ServerTrustPolicyManager, which is responsible for managing the mapping of ServerTrustPolicy objects to a given host.
Now finally, we have got all the prerequisites for Session Manager.
It’s time to build Session Manager with created configurations and serverTrustPolicyManager.
globalManager is SessionManager, which we will be using to make network calls.