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.
Ok, I'm new to xCODE and I have questions about this. Feel free to call me names if they are too simple. In the AppDelegate.m file I try to declare the NSURL and NSURLConnection and got a compiler error about those not beign constants. I implemented the delegate also in AppDelagate.m and that compiles. The NSMutable I have no idea in what method should that go. I'm sure this are simple questions but I really do not know. –
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; } }
I solved the issue. The problem has to do with configuration as the UIWebView is not getting seen as a standard web browser. I'm authenticating user through .net and IIS. I added a generic.browser file in the App_Browser directory of my website. The content of the file is:
for (cookie in [[NSHTTPCookieStoragesharedHTTPCookieStorage] cookies])
{
NSLog([cookie description]);
}
}
트랙백
=================================
=================================
=================================
I have been working using openFrameworks, on a problem that is posted on the forum: www.openframeworks.cc/forum/viewtopic.php?f=8&t=4765
Essentially, I have used an an set of files, ofxHttpUtils, which uses poco to post to web forms. The example code I have used is at: github.com/arturoc/ofxHttpUtils/blob/gh-pages/example/src/testApp.cpp
I want to POST to a login page, a username and password, and then I am aiming to scrape text off the response... that's the aim, via an iPhone app.
The problem I am having is cookies. The ofxHttpUtils addon does not have any method for remembering the cookie from a POST, so the response I get back is just the login page. I have searched for methods to try and capture the cookie, and there seems to be something in Objective C here, from another post to Stack Overflow:
NSHTTPURLResponse * response; NSError * error; NSMutableURLRequest * request; request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60] autorelease]; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]); // If you want to get all of the cookies: NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]]; NSLog(@"How many Cookies: %d", all.count); // Store the cookies: // NSHTTPCookieStorage is a Singleton. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil]; // Now we can print all of the cookies we have: for (NSHTTPCookie *cookie in all) NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate); // Now lets go back the other way. We want the server to know we have some cookies available: // this availableCookies array is going to be the same as the 'all' array above. We could // have just used the 'all' array, but this shows you how to get the cookies back from the singleton. NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]]; NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies]; // we are just recycling the original request [request setAllHTTPHeaderFields:headers]; request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"]; error = nil; response = nil; NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"The server saw:\n%@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);
I am not sure how/where to implement this, so that I can integrate with my my ofxHttpUtils code so that the cookie is remembered and served in calls to the password protected site. Can anyone help? I know this request is a little unspecific... I hope you can see what I'm trying to do...
Since you're already using OF, it would likely be simpler to stick with that. You're going to have to extend ofxHttpUtils to handle cookies, either by making it smarter so it handles cookies intelligently, or by leaving it dumb while letting you grab and set cookies as needed. Poco::Net, which ofxHttpUtils is based on, has no problem with cookies - it includes functions like HTTPResponse::getCookies().
The most straightforward approach is the dumb one:
add ofxHttpForm::setCookies() so you can pass cookies into the module and getCookies()so the module can access them
modify ofxHttpUtils::doPostForm() to pull cookies from the ofxHttpForm and set them on the Poco HTTPRequest
modify the ofxHttpRequest constructor to pull the cookies from the Poco HTTPResponse and provide a way for your code to get at them
Your code would then grab the cookies sent back after the log-in POST and set them on all future requests.
Hi Jeremy thanks for the answer. That had been my thought- but I wasn't sure how to go about it. I think it would involve writing a function within the ofxHttpUtils as you say. But I'm not certain I have the knowledge to do that! But I do agree that mixing the two types of code above is probably not the right thing to do. Do you have any pointers to get me started? Thanks again – sacculiOct 14 '10 at 21:32
@sacculi I've edited my original answer to provide an outline of the straightforward approach, which basically just routes the cookies back and forth through the ofxHttpUtils layer. – Jeremy W. ShermanOct 15 '10 at 0:22
Thanks Jeremy. The steps are really useful, thanks so much. I have tried various ways of implementing them but struggle. Like, passing cookies into the new function (step 1), I guess I need to pass in the HTTPResponse from the postForm function, but I can't get that right. There are some conceptual gaps there, you see, on my part. I was also intrigued by stackoverflow.com/questions/1499086/… which seemed to have the same code as the ofxHttpUtils I have been working with. I wondered about using that somehow, like: – sacculiOct 15 '10 at 12:56
and then after that, req.getCookies( cookies ); after the HTTPRequest for the URL (not the formpost function). But like I said above, I lack some conceptual stuff at this level- I mostly do simple media arts projects! But I shall keep you in touch with my progress, thanks SO much – sacculiOct 15 '10 at 12:59
애플리케이션에서 UIWebView를 사용할 때 쿠키를 저장하는 방법을 살펴본다. 쿠키를 저장하면 애플리케이션이 종료되더라도 로그인 상태 등을 유지할 수 있다. 서버가 특별히 쿠키의 지속 시간을 지정하지 않은 경우 쿠키는 애플리케이션이 종료되면(백그라운드에 남아있는 것과는 다르다) 쿠키 정보는 사라진다.
UIWebView can save and restore cookies. Although application has terminated, the cookies and the session can be restored.
애플리케이션 종료시 쿠키 저장
우선 애플리케이션이 종료되는 이벤트를 잡아야 한다. 현재 멀티태스킹이 지원되는 SDK를 사용하여 애플리케이션을 만든 경우 Application Delegate의 아래 메소드가 호출된다.
쿠키 정보를 저장할 때 UIWebView 인스턴스는 필요 없다 [NSHTTPCookieStorage sharedHTTPCookieStorage] 메소드를 호출하면 애플리케이션에게 할당된 쿠키 저장소를 반환받는다. 즉 시스템 브라우저인 Safari나 다른 애플리케이션과 공유하지 않는 애플리케이션만의 쿠키 저장소이다. (iOS는 쿠키를 공유하지 않지만 Mac OS는 쿠키를 공유한다)
NSDictionary *fields = [HTTPResponse allHeaderFields]; NSString *cookie = [fields valueForKey:\"Set-Cookie\"]; // It is your cookie } //쿠키 문자열을 유지 하거나 복사 합니다.
웹뷰에 쿠키를 할당하거나 또는 별도로 로그인 시 받은 고유 id값을 파라메터로 전달해 주는 방법도 있다. 이는 서버 개발자와 상의해서 쿠키로 처리할 것인지 파라메터로 처리할 것인지 협의 후 결정
고찰.
상태 : 로그인 후 생성된 사용자 정보를 webview에 파라메터로 전달하여 세션 유지
문제 : 로그인 처리 후 webview에 세션을 유지하기 위한 파라메터를 던져서 호출할 경우 초기 loadRequest시 세션이 유지 되지 않아 0.6초 delay를 통해 다시 webView를 같은 url로 loadRequest하여 처리하였으나 네트워크나 서버 상태에 따라 연결되지 않는다.
원하는 방향 : webview 호출 시 한번에 세션을 유지하고 싶음.
테스트 내용 :
1. 로그인 시 NSURLConnection통해 얻은 쿠키값을 저장 후 webview에 전달하였으나, 다른 페이지를 호출하거나 뒤로가기 선택 시 세션 연동이 불안정한 상태로 유지 됨.
2. NSURLConnection를 통한 로그인 후 할당 받은 세션들을 지우고 webview에 파라메터를 던져서 호출 하였으나 세션이 할당되지