简体   繁体   中英

Why do i get authenticationchallenge with NSURLRequest when switching to HTTPS?

I've used NSMutableURLRequest for a long time to connect to my server.

In order to avoid double roadtrips, i set the usr/pwd right away in the header, like this:

NSMutableURLRequest *request = [NSMutableURLRequest
            requestWithURL:[NSURL URLWithString:url]
               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:HTTP_REQUEST_TIMEOUT];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", inUsr, inPwd];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [[authStr dataUsingEncoding:NSISOLatin1StringEncoding] base64EncodedStringWithOptions:0]];

[request setValue:authValue forHTTPHeaderField:@"Authorization"];

This has worked fine, the "willSendRequestForAuthenticationChallenge" is never called unless there is some error, so that method has always looked like:

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {        
    NSDictionary *errorInfo = ((NSHTTPURLResponse *) challenge.failureResponse).allHeaderFields;

    NSError *error; = [NSError errorWithDomain:@"httprequesthandler" code:WRONG_CREDENTIALS userInfo:errorInfo];
    [delegate finishedWithErrors:error];

Now however, i'm using the same URL's as always, only "https" instead of "http", and suddenly this method is called every time.

I want my request to work as per normal, ie populate basic header and only one request to the server.

I'm not sure what i'm missing, so pointers would be much appreciated!

Using https as your scheme (or protocol) requests the connection be made securely, both by encrypting the data that is transferred as well as offering some information to you about the authenticity of the server you are connecting to.

The delegate method being invoked here ( connection:willSendRequestForAuthenticationChallenge: ), is not related to you authenticating yourself with the server, but the server authenticating itself with you. If you dig into the challenge object ( NSURLAuthenticationChallenge ), you can find the credentials the server is offering to let you know that it is the server you were actually trying to connect to, instead of an impostor.

Normally you don't need to use this method unless you want to validate the server in a way that goes beyond what the OS is doing for already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM