swiftssl-certificatealamofire

How can I make Alamofire perform HTTPS request, using a certificate self-signed by an Unknown CA?


I have a webserver that is using a self-signed certificate and I have created a "truststore" based on its certificate.

I am running into the following error:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be "192.168...." which could put your confidential information at risk

Here is some of my implementation:

let pathToCert = Bundle.main.path(forResource: "truststore-root", ofType: "cer")
let localCertificate : NSData = NSData(contentsOfFile: pathToCert! )!

let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
    certificates : [SecCertificateCreateWithData(nil, localCertificate)!],
    validateCertificateChain : true,
    validateHost : false
)

let serverTrustPolicies = [
    "https://192.168.50.31" : serverTrustPolicy
]

return Alamofire.SessionManager(
    configuration: configuration,
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)

Solution

  • First you need to include your self signed ssl certificate in your apps target.

    Note: The certificate must be in a format that iOS can read. You may need to convert your truststore-root.cer file to a different format. In some cases this is a trial and error procedure.

    Then you can adjust your code to use the convenient certificates(in:) function of ServerTrustPolicy like this:

    let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
        certificates: ServerTrustPolicy.certificates(),
        validateCertificateChain: true,
        validateHost: false
    )
    
    let serverTrustPolicies = [
        "192.168.50.31": serverTrustPolicy
    ]
    
    return Alamofire.SessionManager(
        configuration: configuration,
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
    

    This function will scan your main bundle and return all the included files with one of the following suffixes ".cer", ".CER", ".crt", ".CRT", ".der", ".DER".

    UPDATE: You can follow this answer to download your ssl certificate from the terminal. Then double click it to import it to your Keychain. Finaly you can export your certificate from the Keychain as a .cer file. This has the correct format that iOS can read. Verify that this is the case by manually invoking the certificates(in:) function of ServerTrustPolicy. It should now return your certificate.