I have a UIWebView
that loads a website that user Authentication. The site creates an Authentication cookie. When in the browser, unless you clear your cookies, you will always be logged in. When the xCODE loads it can see the cookie listed when looking at the cookie jar but it is not sent to the webView.
I would like to know how to make the webView aware that the auth cookie is there so it does not continue to prompt the user for authentication every single time.
You can use the NSURLConnection class to perform a HTTP request to login the website, and retrieve the cookie. To perform a request, just create an instance of NSURLConnection and assign a delegate object to it.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
Then, implement a delegate method.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSDictionary *fields = [HTTPResponse allHeaderFields];
NSString *cookie = [fields valueForKey:"Set-Cookie"]; // It is your cookie
}
Retain or copy the cookie string. When you want to perform another request, add it to your HTTP header of your NSURLRequest instance.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
[request addValue:cookie forHTTPHeaderField:"Cookie"];
TO delete Cookie anytime you can call this method:
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *each in [[[cookieStorage cookiesForURL:YOUR_URL] copy] autorelease]) {
[cookieStorage deleteCookie:each];
}
You can read the authentication cookie from all websites using the shared cookie storage.
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [cookieJar cookies])
{
NSLog(@"%@", cookie);
}
OR to get the .net aspxauth cookie for your website
NSArray *cookiesForURL = [cookieJar cookiesForURL: [NSURL URLWithString: **MYURL**]];
for (cookie in cookiesForURL)
{
if([cookie.name compare:@".ASPXAUTH"] == NSOrderedSame)
{
NSLog(@"%@", cookie);
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With