Swift:如何使用自签名证书请求URL?

时间:2014-06-05 15:13:52

标签: json ssl swift

我正在打开一个SSL连接以在Swift中检索JSON,但我正在使用自签名证书对我自己的服务器进行测试。以下是网址请求的摘要:

var urlPath = "https://myhost.com/get_json"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)        
connection.start()

但是,由于证书而被拒绝(正确):

Opening connection to https://myhost.com/get_json
2014-06-05 09:37:02.543 AppName[44835:3182593] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Connection failed.The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myhost.com” which could put your confidential information at risk.## Heading ##

3 个答案:

答案 0 :(得分:5)

您需要NSURLConnectionDelegate的其他方法:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace?) -> Bool
{
    return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust
}

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge?)
{
    if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
    {
        if challenge?.protectionSpace.host == "www.myhost.com"
        {
            let credentials = NSURLCredential(forTrust: challenge!.protectionSpace.serverTrust)
            challenge!.sender.useCredential(credentials, forAuthenticationChallenge: challenge)
        }
    }

    challenge?.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

注意:仅在使用异步NSURLConnection时才可以这样做。

答案 1 :(得分:0)

这是我对Swift3的解决方案

let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)


extension WebServiceManager : URLSessionDelegate {
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

        var trustedHostArray = [String]()

        if Utils.getEnviroment() == Constants.Environment.Production.rawValue {
            trustedHostArray = Constants.TRUSTED_HOSTS.Production
        } else {
            trustedHostArray = Constants.TRUSTED_HOSTS.Develop
        }

        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            if trustedHostArray.contains(challenge.protectionSpace.host) {
                let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
                challenge.sender?.use(credential, for: challenge)
                completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)
            }
        }
    }
}

答案 2 :(得分:0)

我已经更新了Erik对Swift 3的回答:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace?) -> Bool {
    return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust
}

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge?) {
    if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
    {
        if challenge?.protectionSpace.host == "www.myhost.com"
        {
            let credentials = URLCredential(trust: challenge!.protectionSpace.serverTrust!)
            challenge!.sender?.use(credentials, for: challenge!)
        }
    }

    challenge?.sender?.continueWithoutCredential(for: challenge!)
}