Alamofire with a Self-Signed Certificate/Servertrustpolicy

Alamofire 5 with self-signed certificate

It's very similar in Alamofire 5 but ServerTrustPolicy has been refactored into a protocol with conforming types for better extensibility. Similar to the answer you linked, you'll need to create a ServerTrustManager for your domain:

let manager = ServerTrustManager(evaluators: ["your.domain.here": DisabledTrustEvaluator()])
let session = Session(serverTrustManager: manager)

Of course, you'll still need to add ATS exceptions for your domains as well.

Additionally, you should never ship code that uses the DisabledTrustEvaluator, as it would allow all invalid TLS connections.

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

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.

Secure JSON Request via Alamofire and Self-Signed Certificates

let manager: Alamofire.SessionManager = {
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"https://sensemp.ru": .pinCertificates(
certificates: ServerTrustPolicy.certificates(),
validateCertificateChain: true,
validateHost: true),
"sensemp.ru": .disableEvaluation
]
  • add ip from hosts into certificate DNS section

enter image description here

How to securely upload files with Alamofire in a local server using TLS and self-signed certificates?

I've implemented something similar:

  1. Copy your self signed certificate into your XCode project. Lets call this certificate "myCert.der"

  2. Setup an Alamofire secure session manager with your signed certificate. It will be something like this.

    var secureSessionManager = Alamofire.SessionManager()
    func configureAlamoFireSSLPinning() {

    let pathToCert = Bundle.main.path(forResource: "myCert", ofType: "der")
    let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!

    if #available(iOS 10.3, *) {
    let STP = ServerTrustPolicy.pinPublicKeys(
    publicKeys: [SecCertificateCopyPublicKey(SecCertificateCreateWithData(nil, localCertificate)!)!],
    validateCertificateChain: true,
    validateHost: true)

    let serverTrustPolicies = [
    "myhost.com": STP
    ]

    secureSessionManager = Alamofire.SessionManager(
    configuration: URLSessionConfiguration.default,
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
    }
    }
  3. Call the function to setup your secure session manager:
    configureAlamoFireSSLPinning()

  4. Make your requests using this alamofire secure session manager. All requests made through this manager will be secure:

    secureSessionManager.request("https://host.com/myrequest", method:.get).responseJSON { response in 

    switch response.result {
    case .success(let value):
    //Do stuff
    case .failure(let error):
    print(error)

    }
    }

    For more information, you can visit Alamofire's documentation on security:
    https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security

How to connect to self signed servers using Alamofire 1.3

There is a way to change the Server Trust Policy of the Alamofire manager shared instance, but it's not recommended. Instead you should create your own customised instance of the manager. Here is the recommended solution, code is Swift 2.0 with Alamofire from swift-2.0 branch, compiled in Xcode7 beta 5.

Creating customised instance of the manager

Because you will not use the request method on the Alamofire, but use the one on your custom manager instead, you need to think of where to store the manager. What I do is to store it as static in my networking wrapper (the class that utilizes Alamofire and deals with my application networking needs). I set it up like this:

private static var Manager : Alamofire.Manager = {
// Create the server trust policies
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"maskeddomain.com": .DisableEvaluation
]
// Create custom manager
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
let man = Alamofire.Manager(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
return man
}()

Next step is to switch all your calls that use Alamofire.request() with Manager.request(), so you should have something like this:

Manager.request(.GET, "http://stackoverflow.com").responseJSON(
completionHandler: { (_, respose, result) -> Void in
if result.isSuccess {
// enjoy your success
} else if result.isFailure {
// deal with your failure
}
})

If you want to change the shared instance of the manager anyway, go here for more info.

How to implement self signed certificates in Alamofire?

This feature is not yet supported by Alamofire. It will most likely be added eventually by the community, but that work has yet to be submitted to the project. If you feel like contributing this feature, by all means fork the repo and submit a pull request.

If you want to learn how to implement this feature yourself, I'd suggest you read up on SSL pinning and TLS verification on iOS. You could also browse the source code in AFNetworking to get a feel of how it could possibly be implemented.

If you do not have time to build this feature yourself, then I suggest you use AFNetworking for the time being in your Swift app. AFNetworking is perfectly compatible with Swift and does support TLS verification.



Related Topics



Leave a reply



Submit