Home > OS >  how to do SSL public key pinning in Alamofire swift 5
how to do SSL public key pinning in Alamofire swift 5

Time:08-05

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.

CodePudding user response:

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.

  • Related