Adding authentiction headers to request before sending to stop challenge

responses from being generated server-side on each request. This should
cut down overall request-response cycles by 50% when dealing with
authenticated services.
This commit is contained in:
Marc Weil
2010-12-05 12:07:41 -05:00
parent fbe8457dd7
commit f3af0feefc
2 changed files with 12 additions and 15 deletions

View File

@@ -70,7 +70,18 @@
if ([_params respondsToSelector:@selector(HTTPHeaderValueForContentLength)]) {
[_URLRequest setValue:[NSString stringWithFormat:@"%d", [_params HTTPHeaderValueForContentLength]] forHTTPHeaderField:@"Content-Length"];
}
}
}
if (_username != nil) {
// Add authentication headers so we don't have to deal with an extra cycle for each message requiring basic auth.
CFHTTPMessageRef dummyRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (CFStringRef)[self HTTPMethod], (CFURLRef)[self URL], kCFHTTPVersion1_1);
CFHTTPMessageAddAuthentication(dummyRequest, nil, (CFStringRef)_username, (CFStringRef)_password, kCFHTTPAuthenticationSchemeBasic, FALSE);
CFStringRef authorizationString = CFHTTPMessageCopyHeaderFieldValue(dummyRequest, CFSTR("Authorization"));
[_URLRequest setValue:(NSString *)authorizationString forHTTPHeaderField:@"Authorization"];
CFRelease(dummyRequest);
CFRelease(authorizationString);
}
NSLog(@"Headers: %@", [_URLRequest allHTTPHeaderFields]);
}

View File

@@ -52,20 +52,6 @@
[super dealloc];
}
// Handle basic auth
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential=[NSURLCredential credentialWithUser:[NSString stringWithFormat:@"%@", _request.username]
password:[NSString stringWithFormat:@"%@", _request.password]
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential
forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (NO == _loading) {
_loading = YES;