由于不受信任的证书

由于不受信任的证书

本文介绍了由于不受信任的证书,无法通过HTTPS接收JSON请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在谷歌搜索这个问题几个小时了,我似乎无法找到解决方案。

I have been googling this problem for hours now, and I can't seem to find a solution.

我接下来的最后一个教程是解释了如何通过不受信任的SSL连接发送JSON请求(在本例中为自签名)证书)。

The last tutorial I followed was this tutorial explaining how I could send a JSON request over an untrusted SSL connection (in this case, a self-signed certificate).

简而言之,我到目前为止尝试过的代码是这样的:

In short, the code I have tried so far is this one:

此方法检查如果令牌对我的网络API有效:

This method checks if the token is valid with my web API:

-(BOOL)linked
{
    if([self token] == nil)
    {
        return NO;
    }else
    {
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?token=%@&object=User&action=check_authorized", SPAtajosApiLink, [self token], nil]];
        NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
        [req setHTTPMethod:@"POST"];
        NSLog(@"%@", req);
        [req setHTTPBody: [mandatoryParameters dataUsingEncoding: NSUTF8StringEncoding]];

        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
        [connection start];

        NSDictionary *validity = [NSJSONSerialization
                                  JSONObjectWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil]
                                  options:NSJSONReadingMutableContainers
                                  error:nil];
        NSLog(@"RESPONSE LINKED %@ %@", validity[@"code"], validity[@"message"]);
    }
    return YES;
}

我已经实现了NSURLConnectionDelegate方法,如下所示:

And I have implemented the NSURLConnectionDelegate methods as follows:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        NSLog(@"API LINK %@", challenge.protectionSpace.host);
        if ([challenge.protectionSpace.host isEqualToString:SPAtajosApiLink])
        {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        }
    }

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

然而,我的应用程序总是崩溃,并显示以下消息:

Yet, my app always crashes with the following message:

好的,所以NSData,可能是NSJSONSerialization中的参数是NULL。问题是,为什么?

Okay, so NSData, presumably the parameter in NSJSONSerialization is NULL. The question, why?

奇怪的是,我有一个类似的代码,它实际上适用于通过不受信任的SSL与网站交互的UIWebView:

Bizarrely enough I have a similar code that actually works with a UIWebView interacting with a website over untrusted SSL:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //Need to rebuild base URL. Otherwise I get the parameters which will always fail the check.
    NSURL *requestUrl = [request URL];
    NSString *basicPathString = [NSString stringWithFormat:@"%@://%@:%@%@", requestUrl.scheme, requestUrl.host, requestUrl.port, requestUrl.path];
    NSLog(@"%@", basicPathString);

    if([basicPathString isEqualToString:SPAtajosLoginLink])
    {

        __block NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:request.URL.absoluteURL]
                                                                             options:NSJSONReadingMutableContainers
                                                                               error:nil];
        NSLog(@"Auth token is %@", jsonResponse[@"token"]);
        [self dismissViewControllerAnimated:YES completion:^{
            if([jsonResponse[@"code"] isEqualToNumber:[NSNumber numberWithInt:200]])
            {
                [[PDKeychainBindings sharedKeychainBindings] setObject:jsonResponse[@"token"]
                                                                forKey:@"com.shortcutpublicity.ios.atajos.userAccessToken"];
            }else
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No Se Pudo Autenticar", @"Error 500 title")
                message:NSLocalizedString(@"Se ha producido un error interno del servidor (500). Por favor, trata de nuevo más tarde.", @"Error describing error 500")
                delegate:nil
                cancelButtonTitle:NSLocalizedString(@"Aceptar", @"Accept") otherButtonTitles:nil];
                [alertView show];
            }
         }];
    }else {
    //--------------THIS IS THE RELEVANT PART------------
        BOOL result = _Authenticated;
        if (!_Authenticated)
        {
            _FailedRequest = request;
            NSURLConnection *trash = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            if(trash)
            {
                NSLog(@"Allocated succesfully.");
            }
        }
        return result;
    }
    return YES;
}

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURL* baseURL = [NSURL URLWithString:SPatajosAuthLink];
        if ([challenge.protectionSpace.host isEqualToString:baseURL.host]) {
            NSLog(@"trusting connection to host %@", challenge.protectionSpace.host);
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        } else
            NSLog(@"Not trusting connection to host %@", challenge.protectionSpace.host);
    }
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)pResponse {
    _Authenticated = YES;
    [connection cancel];
    [_webView loadRequest:_FailedRequest];
}

我试图调整这个适用于WebView的代码,但我没有'有任何运气适应与NSURLConnection一起使用。

I have tried to adapt this code that works with a WebView but I haven't had any luck adapting to use it with a NSURLConnection.

说实话,我不是相当确定我知道这些变通办法是如何工作的。我一直在窃取并试图调整其他人的代码无济于事。我查看了NSURLConnection和NSURLRequest文档,但我无法解决这些问题。请帮帮我。

To be honest, I'm not quite sure I know how these workarounds work. I have been stealing and attempting to adapt other people's code to no avail. I have looked at NSURLConnection and NSURLRequest docs and I wasn't able to solve these problems. Please help me out.

推荐答案

我们在#ifedf块中使用此类别进行测试...确保你不要离开这在生产中:

We use this category in an #ifedf block for testing... make sure you DO NOT leave this in production:

#ifdef DEBUG
@interface NSURLRequest (IgnoreSSL)
   +(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
@end
@implementation NSURLRequest (IgnoreSSL)
   +(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host {return YES;}
@end
#endif

这篇关于由于不受信任的证书,无法通过HTTPS接收JSON请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:36