【问题标题】:AuthenticationMethodServerTrust is nil in iOS 9AuthenticationMethodServerTrust 在 iOS 9 中为零
【发布时间】:2016-03-03 09:54:07
【问题描述】:

我一直在尝试使用 NSURLSession 在我的 iOS 8+ 应用中实现公钥固定。

我所做的只是实现委托方法 didReceiveChallenge 并获取 challenge.protectionSpace.authenticationMethod 并检查它是否等于 NSURLAuthenticationMethodServerTrust。

如果它等于 NSURLAuthenticationMethodServerTrust,我会检查证书并将其与我的本地副本进行比较。

这在 iOS 8 上运行良好,但在 iOS 9 上我没有收到等于 NSURLAuthenticationMethodServerTrust 的身份验证方法。我收到 NSURLAuthenticationMethodClientCertificate 所以我无法访问 challenge.protectionSpace.serverTrust 属性。

有什么想法吗?

public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)
{


      if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust)
        {
            // Verify the identity of the server
                    println("Trusted")
                    return challenge.sender.performDefaultHandlingForAuthenticationChallenge!(challenge)

        }
        println("Not trusted")
        return challenge.sender.cancelAuthenticationChallenge(challenge)
    }
}

【问题讨论】:

标签: ios swift authentication nsurlsession nsurlsessiontask


【解决方案1】:

您的回调可以针对不同的保护空间多次调用。这里发生的情况是这些调用的顺序发生了变化,并且服务器信任保护空间调用显然由于某种原因在 iOS 9 中没有首先发生。

问题在于您取消了第一个质询,这实际上终止了连接。不要那样做。而是使用“执行默认处理”。

您也可能不希望对服务器信任案例执行默认处理,因为这相当于根本不编写自定义处理程序。相反,检查密钥,仅当它是您想要的密钥时才执行默认处理,否则取消身份验证质询。

或者我误读了您的代码。似乎缺少一些代码。可能是您根本没有处理非服务器信任案例,在这种情况下,这就是问题所在。如果您不为每个挑战调用something,则连接将永远停留在那里,等待您这样做。

【讨论】:

  • 谢谢@dgatwood。你拯救了我的一天 :) 显然是 iOS 9,首先调用 ClientCertificateChallenge 所以我刚刚添加: ... else if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate) { completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil); }
  • 仅供参考,我所说的实际上是错误的。服务器信任的默认处理很好。它告诉它使用证书而不检查它会很糟糕。 :-)
猜你喜欢
  • 2021-05-15
  • 2017-03-20
  • 2016-01-23
  • 2016-04-07
  • 2015-12-30
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多