I am trying to integrate SSL public key pinning in Alamofire swift 5, but I found ServerTrustPolicyManager
which is deprecated. Please help me to integrate. Thanks.

- 7,729
- 3
- 20
- 37

- 55
- 2
- 10
1 Answers
To integrate SSL public key pinning you first have to add your SSL certificate in your project's target by dragging and dropping it.
To test if your certificate is in the correct format you can try to get the value from publicKeys
parameter of the AlamofireExtension
in your main Bundle
, like this:
print("Bundle public keys: \(Bundle.main.af.publicKeys)")
If that array have at least one element, then you are ready. If it does not, then try importing your SSL certificate to your Mac's Keychain, then export it as .cer
and then add it to your project's target. (this should work)
To check if the public key of the SSL certificate is the one that you import in your project you can use the Alamofire's ServerTrustManager
with a PublicKeysTrustEvaluator
instance, when you create your Session
:
let evaluators: [String: ServerTrustEvaluating] = [
"your.domain.com": PublicKeysTrustEvaluator()
]
let serverTrustManager = ServerTrustManager(evaluators: evaluators)
let session = Session(serverTrustManager: serverTrustManager)
Make sure that in the evaluators
dictionary, the key ("your.domain.com"
in the code above) is your servers domain and if you don't want for Alamofire to perform the default validation and/or validate the host you can pass false
to those parameters in PublicKeysTrustEvaluator
's initializer:
let evaluators: [String: ServerTrustEvaluating] = [
"your.domain.com": PublicKeysTrustEvaluator(
performDefaultValidation: false,
validateHost: false
)
]
let serverTrustManager = ServerTrustManager(evaluators: evaluators)
let session = Session(serverTrustManager: serverTrustManager)
Then you have to use this Session
instance to make any request in your domain, like this:
let url = "https://your.domain.com/path/to/api"
session.request(url, method: .post, parameters: parameters).responseDecodable { response in
}
As @JonShier pointed out in the comments: You need to keep your Session
alive beyond the declaring scope. Usually this is done through a single or other outside reference.

- 7,729
- 3
- 20
- 37
-
after adding as per your suggestion i am getting **Request failed with error sessionDeinitialized** error. Can you please suggest step by step – Bhimashankar Aug 04 '22 at 10:40
-
@Bhimashankar in order for this code to work you have to add you SSL certificate in your app's bundle. Did you do that step? – gcharita Aug 04 '22 at 10:50
-
yes, i added .der certificate file in project bundle. Please explain step by step it will helpful for me to understand. thanks – Bhimashankar Aug 04 '22 at 10:57
-
2You need to keep your `Session` alive beyond the declaring scope. Usually this is done through a single or other outside reference. – Jon Shier Aug 04 '22 at 19:12
-
@ gcharita, Jon Shier thanks its working – Bhimashankar Aug 05 '22 at 08:39