I'm building an iOS app that uses Google App Engine for the backend. Google provides an HTML login site that stores an authentication cookie. If I visit that site in a UIWebView, and the user logs in, will those cookies be in storage where they will be picked up by a NSURLConnection when making a request to the same site?
Asked
Active
Viewed 1.2k times
24
-
Thanks. I've been trying to figure out a way to ask this question for about 10 minutes now. – Dan Rosenstark Mar 24 '15 at 17:33
-
1@Yar: Glad you found it then! – Linuxios Mar 24 '15 at 17:33
1 Answers
22
The cookie of the UIWebView will be stored in a sandboxed cookie storage accessible through NSHTTPCookieStorage sharedHTTPCookieStorage]
. You can use this cookie storage in NSURLConnection in this way:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"__YOUR_URL__"]];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setAllHTTPHeaderFields:headers]; //A previously created NSMutableURLRequest
Now you can normally use the NSURLRequest in a NSURLConnection and it will send the cookies created after the login in the UIWebView

mattsven
- 22,305
- 11
- 68
- 104

Antonio E.
- 4,381
- 2
- 25
- 35
-
Do I replace `"YOUR_URL"` with the URL of the page, or of the domain? – Linuxios Mar 13 '13 at 23:24
-
In your case replacing YOUR_URL with `.google.com` should be fine, in general that is the url that match the domain field of the cookie. If you don't know what is the exact url (`.google.com` match all google.com subdomains) you can get all the cookie in the cookie storage in this way: `[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]`. Probably the server will simply ignore the cookies (if you have others) that are not for him. – Antonio E. Mar 14 '13 at 11:50
-
exactly. You can refer to the rfc that specifies the http state management mechanism for more about how domains are matched in cookies [rfc 6265](http://tools.ietf.org/html/rfc6265). – Antonio E. Mar 14 '13 at 13:45
-
-
3Well, never send all cookies to a random server like @AntonioE. suggests. Yes, the server will probably ignore them, but if they don't you could be sending login/authentication tokens over to a server you don't know. That would be quite a security vulnerability... – Mac_Cain13 Aug 26 '14 at 12:10
-
@Mac_Cain13 you are absolutely right. When I wrote the question I simply assumed that since he is working with his own requests in his own application probably the other cookies are not really important. But yes you shouldn't send all of them. – Antonio E. Feb 13 '15 at 12:27