使用https的NSMutableURLRequest会导致验证失败

时间:2012-07-11 10:15:28

标签: ios xcode

url的连接请求方法(https://xxxx.xxxx.xx/MobileService/Service.svc/login :),

编辑:

似乎我无法通过https连接进行身份验证。 http工作正常。你知道为什么吗?

代码:

NSString *postData = @"{}";
NSData *requestData = [postData dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:allAppsURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connectionDict setObject:connection forKey:@"all"];

认证方法:

// If the application needs to authenthicate
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
    NSLog(@"received authentication challenge");



    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"TamTam" accessGroup:nil];
    NSString *password = [keychainItem objectForKey:kSecValueData];
    NSString *username = [keychainItem objectForKey:kSecAttrAccount];
    username = [@"\\" stringByAppendingString:username];

    NSURLCredential *newCredential = [[[NSURLCredential alloc] initWithUser:username password:password
                                                                persistence:NSURLCredentialPersistenceForSession] autorelease];

    NSLog(@"credential created");
    [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
    NSLog(@"responded to authentication challenge");   

}
else {

    // pull from server is always two connections, all and sub. To prevent multiple messages from pull do not check sub
    if(!(connection == [connectionDict objectForKey:@"sub"])){
        [[self delegate] serverConnection:NO process:@"login"];
    }
    NSLog(@"previous authentication failure");
}
}

1 个答案:

答案 0 :(得分:0)

你可能还需要添加 - (BOOL)连接:(NSURLConnection *)连接canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace