I would like to support HTTP Basic Authentication in my UIWebView.
At the moment, I am canceling requests in
webView:shouldStartLoadWithRequest:navig
I've just implemented this by setting basic auth credentials using an NSMutableURLRequest
for the UIWebView
. This also avoids the round trip incurred when implementing sharedCredentialStorage
(of course there are tradeoffs involved).
Solution:
NSString *url = @"http://www.my-url-which-requires-basic-auth.io"
NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[mutableRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
NSURLRequest *request = [mutableRequest copy];
NSURLRequest *request = [NSURLRequest basicAuthHTTPURLRequestForUrl:url];
[self.webView loadRequest:request];
You can grab the NSData+Base64 category which implements the base64EncodedString
for NSData from Matt Gallagher's page (it was at the bottom of the blog post when I downloaded it)