Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the Authentication Challenge in UIWebView?

I am trying to access a secure website through UIWebView. When I access it through safari, i get an authentication challenge but the same does not appear in my UIWebView in the application. How can I make it appear?

Any pointers, sample code or links will be very helpful. Thanks a lot.

like image 290
UVT Avatar asked Nov 20 '09 11:11

UVT


1 Answers

It's actually super easy... I'm sure you can just show a UIAlertView when the auth challenge delegate is shown (or prior to loading the URL, if you know for sure that the URL you're hitting will prompt for auth login info). Anyways, the trick is to create your own NSURLConnection and I do some logic to save whether the auth delegate has been used.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {     NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authed);      if (!_authed) {         _authed = NO;         /* pretty sure i'm leaking here, leave me alone... i just happen to leak sometimes */         [[NSURLConnection alloc] initWithRequest:request delegate:self];         return NO;     }      return YES; }  - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; {     NSLog(@"got auth challange");      if ([challenge previousFailureCount] == 0) {         _authed = YES;         /* SET YOUR credentials, i'm just hard coding them in, tweak as necessary */         [[challenge sender] useCredential:[NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistencePermanent] forAuthenticationChallenge:challenge];     } else {         [[challenge sender] cancelAuthenticationChallenge:challenge];     } }  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; {     NSLog(@"received response via nsurlconnection");      /** THIS IS WHERE YOU SET MAKE THE NEW REQUEST TO UIWebView, which will use the new saved auth info **/      NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:]];      [_webView loadRequest:urlRequest]; }  - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection; {     return NO; } 
like image 156
Sahil Avatar answered Oct 21 '22 23:10

Sahil