如何使用Alamofire连接localhost(使用无效证书)?

Ism*_*ail 15 certificate swift alamofire

这是我使用swift的第一个项目.我是alamofire连接API.我有一个本地副本形式我想用于调试的API - 所以我可以设置测试数据 - 因为远程API已经有我无法搞砸的真实数据.

问题是我尝试访问时遇到以下错误 https://localhost:8443/MyProject

可选(错误域= NSURLErrorDomain代码= -1202"此服务器的证书无效.您可能连接到假冒"localhost"的服务器,这可能会使您的机密信息面临风险."UserInfo = 0x7fbeb8c61ff0 {NSURLErrorFailingURLPeerTrustErrorKey = ,NSLocalizedRecoverySuggestion =你想连接到服务器吗?,_kCFStreamErrorCodeKey = -9813,NSUnderlyingError = 0x7fbeb8ea5c00"操作无法完成.(kCFErrorDomainCFNetwork error -1202.)",NSLocalizedDescription =此服务器的证书无效.您可能连接到假冒"localhost"的服务器,这可能会使您的机密信息面临风险.,NSErrorFailingURLKey = https:// localhost:8443/myproject/api/loginUser.pdo,NSErrorFailingURLStringKey = https:// localhost :8443/myproject/api/loginUser.pdo,_kCFStreamErrorDomainKey = 3})

我发现许多解决方案大部分都是针对Objective-c使用setAllowsAnyHTTPSCertificate或使用Connection的委托.但是我无法setAllowsAnyHTTPSCertificate在swift中找到一个有效的方法,我不知道如何在使用alamofire时将委托设置为连接.任何想法我需要做什么?

  • 我知道这setAllowsAnyHTTPSCertificate是私人api,会导致该项目被Apple拒绝.我只想在调试时使用它,然后在发布项目之前将其删除.

先感谢您.

cno*_*oon 20

您可以使用SessionDelegate覆盖闭包轻松覆盖Alamofire中的默认质询行为.以下是如何允许Alamofire接受无效证书的示例:

重要提示:请不要在任何生产代码中使用它.安全性非常重要,这种实现完全忽视了Alamofire中的安全机制.使用风险自负!

let manager = Alamofire.Manager.sharedInstance

manager.delegate.sessionDidReceiveChallenge = { session, challenge in
    var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
    var credential: NSURLCredential?

    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        disposition = NSURLSessionAuthChallengeDisposition.UseCredential
        credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
    } else {
        if challenge.previousFailureCount > 0 {
            disposition = .CancelAuthenticationChallenge
        } else {
            credential = manager.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)

            if credential != nil {
                disposition = .UseCredential
            }
        }
    }

    return (disposition, credential)
}
Run Code Online (Sandbox Code Playgroud)

我们(Alamofire TC)将在Alamofire 1.3.0版本中实现TLS钉扎和其他一些与安全性相关的功能.


UPDATE

Alamofire 1.3.0版本已经发布,为定制服务器信任身份验证挑战提供了更好的支持.有关详细信息,请查看自述文件的安全性部分.