我正在寻找一种实现能够切换我的Web应用程序用来与给定服务器通信的NSURLCredential的方法。

有没有一种方法可以为给定的服务器信任“重置” NSURLCredential ssl凭据,并使用不同的凭据集强制整个握手过程重复进行?换句话说,我希望我的Web应用程序忘记与该服务器对话过的内容。

我认为下面的代码片段正在检索我之前评估过的证书。

- (void)customHTTPProtocol:(CustomHTTPProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

NSURLCredential *   credential = nil;
SecTrustRef         trust;
NSURLProtectionSpace* protectionSpace = challenge.protectionSpace;
  if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            //this verifies that we are talking to a server that we trust by checking it's certificate


            // Extract the SecTrust object from the challenge, apply our trusted anchors to that
            // object, and then evaluate the trust.  If it's OK, create a credential and use
            // that to resolve the authentication challenge.  If anything goes wrong, resolve
            // the challenge with nil, which continues without a credential, which causes the
            // connection to fail.
            trust = [protectionSpace serverTrust];
            if (trust == NULL) {
                assert(NO);
            } else {
                // Just Ignore Self Signed Certs
                SecTrustResultType result;

                //This takes the serverTrust object and checkes it against your keychain
                SecTrustEvaluate(protectionSpace.serverTrust, &result);
                //if we want to ignore invalid server for certificates, we just accept the server
                credential = [NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust];
                if(result == kSecTrustResultProceed ||
                          // result == kSecTrustResultConfirm || // Deprecated - Remove?
                          result == kSecTrustResultUnspecified) {

                    [challenge.sender useCredential:credential forAuthenticationChallenge: challenge];
                }
            }
            [protocol resolveAuthenticationChallenge:challenge withCredential:credential];
        }

//... more ways to resolve challenge
}

最佳答案

我尝试了各种方法来实现这一目标,但全部都是如此。

但是一个简单的技巧就起作用了。

为了强制我的网页重新进行身份验证,我将在请求网址的末尾添加以下内容。

&r=1100910192 **(timestamp)**

因此,实际上不用重新缓存就可以使用已验证的凭据。

在其他情况下,只需在请求末尾添加#即可:

[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/some.json#"]]


希望对您有所帮助。

09-30 15:01
查看更多