1

I am trying to configure my iOS app to accept self-signed certificates. I am trying to fetch the data on a button click. Below is the code that I am using currently:

private var manager : SessionManager?

func setManager(url: String) {
    let serverTrustPolicies: [String: ServerTrustPolicy] = [
        url: .disableEvaluation
    ]

    let configuration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders

    manager = Alamofire.SessionManager(
        configuration: configuration,
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
}

@IBAction func nonCertifiedClick(_ sender: UIButton) {
    outputText.text = ""

    setManager(url: "sand.xxx.int:16443")
    manager?.request("https://sand.xxx.int:16443/version").response { response in
        debugPrint("R: \(response)")

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")
            self.outputText.text = utf8Text
        }
    }
}

My Info.plist file has the below configuration:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict> 

But when the request is executed, I get the following response:

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
"R: DefaultDataResponse(request: Optional(https://sand.xxx.int:16443/version), response: nil, data: Optional(0 bytes), 
error: Optional(Error Domain=NSURLErrorDomain Code=-1202 \"The certificate for this server is invalid. You might be connecting to a server that is pretending to be “sand.xxx.int” which could put your confidential information at risk.\" 
UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x600000105730>, 
NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, 
_kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, 
NSErrorPeerCertificateChainKey=(\n    \"<cert(0x7fcf8b81e800) s: sand i: sand>\"\n), 
NSUnderlyingError=0x60000005f440 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 \"(null)\" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, 
kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x600000105730>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, 
_kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, 
kCFStreamPropertySSLPeerCertificates=(\n    \"<cert(0x7fcf8b81e800) s: sand i: sand>\"\n)}},

NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “sand.xxx.int” which could put your confidential information at risk., 
NSErrorFailingURLKey=https://sand.xxx.int:16443/version,
 NSErrorFailingURLStringKey=https://sand.xxx.int:16443/version, NSErrorClientCertificateStateKey=0}), 
_metrics: Optional((Task Interval) <_NSConcreteDateInterval: 0x600000224e40> (Start Date) 2016-11-02 14:13:57 +0000 + (Duration) 0.381569 seconds = (End Date) 2016-11-02 14:13:58 +0000\n(Redirect Count) 0\n(Transaction Metrics) (Request) <NSURLRequest: 0x600000200120> { URL: https://sand.xxx.int:16443/version }\n(Response) (null)\n(Fetch Start) 2016-11-02 14:13:57 +0000\n(Domain Lookup Start) (null)\n(Domain Lookup End) (null)\n(Connect Start) (null)\n(Secure Connection Start) (null)\n(Secure Connection End) (null)\n(Connect End) (null)\n(Request Start) 2016-11-02 14:13:57 +0000\n(Request End) 2016-11-02 14:13:57 +0000\n(Response Start) 2016-11-02 14:13:57 +0000\n(Response End) (null)\n(Protocol Name) (null)\n(Proxy Connection) NO\n(Reused Connection) YES\n(Fetch Type) Unknown\n\n))"
Data: 

I am testing this on Xcode 8.1 with Swift3 and Alamofire4. What am I misisng here to make it work right?

Update (Answer) If incase someone encounters the same issue, the problem was the server's SSL certificate. The certificate needs to be signed with at least SHA256 algorithm but mine was signed with SHA1.

Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
  • 1
    duplicate of http://stackoverflow.com/questions/32553414/alamofire-with-a-self-signed-certificate-servertrustpolicy – Ankit Thakur Nov 02 '16 at 18:40
  • Possible duplicate of [Alamofire with a self-signed certificate / ServerTrustPolicy](https://stackoverflow.com/questions/32553414/alamofire-with-a-self-signed-certificate-servertrustpolicy) – Lepidopteron Oct 17 '17 at 06:39

1 Answers1

1

I faced the same problem. But using your question, i found the solution. Tnx..

Here is my solution. it works with swift 3

create a class SecurityCertificateManager

import Foundation
import Alamofire


class SecurityCertificateManager {
    static let sharedInstance = SecurityCertificateManager()

    let defaultManager: Alamofire.SessionManager = {
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "272.73.41.156": .disableEvaluation
        ]

        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders

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

call it like this in viewDIdLoad

let baseUrl ="https://272.73.41.156/cas/tickets?"+"username="+userEmail.text!+"&password="+userPassword.text!
        print("Base url : \(baseUrl)")

        let params2 = ["nostring": "nodata", "nostring": "nodata",]

        SecurityCertificateManager.sharedInstance.defaultManager.request(baseUrl, method: .post, parameters: params2, encoding: JSONEncoding.default, headers: ["Content-Type":"application/x-www-form-urlencoded"]).responseJSON { (response:DataResponse<Any>) in

            switch(response.result) {
            case .success(_):
                if response.result.value != nil{
                    print("response : \(response.result.value)")
                }
                break

            case .failure(_):
                print("Failure : \(response.result.error)")
                break

            }
        }

It Works in Swift3

Sathya Baman
  • 3,424
  • 7
  • 44
  • 77