web view cookie 詳解

https://medium.com/@mahithegeek/cookies-in-ios-nshttpcookie-and-nshttpcookiestorage-696564bc6975

Cookies in iOS— NSHTTPCookie and NSHTTPCookieStorage

What is a Cookie?

Cookies generally are very common and widely used in browser world, mainly for Session Management, User preferences and state etc.?Cookie?is a small piece of data with some attributes sent by servers. This is stored by Web browsers and shared with server in the subsequent requests.

Structure of a Cookie

Even though a Cookie is small piece of data, it follows a structure and each attribute defines the behavior of the cookie. The RFC documents are very useful?:?RFC 6265?and?RFC 2109

If you are interested to see some cookies at work in real time?, open a browser and hit any url like google or Facebook. In chrome open dev tools (you can open this by right click and say inspect) and in the network section go to Headers and see the cookie. In Safari open webinspector and go to Resources and you can see cookie in request headers.

HTTP cookies

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The…developer.mozilla.org

Cookies and Mobile Apps

Cookies are used frequently in the Web world, lot of times Mobile Developers do not need to deal with them. They always have nice REST APIs to hit and fetch data from server any time. This is true for most use cases and apps. But some times the borders are blurred and requirements come up, where there may be a need to handle cookies and perform some tasks from mobile apps as well.

A good example can be Single Sign On (SSO) situations. If the enterprise has some services and data accessible via SSO along with REST APIs for some other data then it could be possible that the mobile app may need to access these SSO protected resources. In SSO users log in only once and access all the resources protected under the same SSO. SSO solutions generally use cookies to achieve this. Hence cookie handling may be required by the app to comply and operate with SSO systems.

How do we handle Cookies in iOS?

iOS has good ways and means to handle cookies. Classes?NSHTTPCookie?and?NSHTTPCookieStorage?are well designed and have nice APIs and attributes to represent a cookie and store it as well. But there is very limited documentation available and less content on Stack Overflow on this topic. (no surprise this is not a common use case)

So lets try to explore:

Method 1:

You can “cook up” or “bake” a custom cookie using the code above. NSHTTPCookie class does allow a cookie to be constructed, by passing in different attributes. There are certain mandatory parameters to successfully create a cookie. We at least need name, value, domain or originurl and path. See?here. If these are not provided, the API returns a nil cookie.

Below is a code snippet:

There are many other attributes for the cookie and some can’t be set using the above method. For example, the attribute?HttpOnly?which is a very important paramter in a Cookie, can’t be set via properties dictionary like above.

In my opinion, creating a cookie like this using the above code may not be very useful and it may not do the things that you want. Definitely not useful in SSO environment. Also you need to write more code if there are multiple cookies and also make sure the properties are correctly formed for each cookie.

Method 2 (recommended):

There is another great API in the NSHTTPCookie class where you can dump the entire http response string and the class would return a perfect cookie (array of cookies) by setting all the necessary attributes including the HttpOnly.(in fact this is the only way to set all the attributes)

NSArray* httpCookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[httpresponseallHeaderFields]forURL:url;

In the http response from the server, cookies generally come as key value pair, with Key “Set-Cookie:”. The above API picks the cookie string from the response and converts it into a meaningful cookie.?The URL in the above API is very useful and important.?Earlier we said there are four mandatory parameters for a cookie to be created in iOS, name, domain, value and path. But according to RFC docs, Domain can be optional which means Cookies might have an empty domain some times.?There is no property to set originURL in the NSHTTPCookie Class either. In such cases Method #1 is completely useless.?But in the current method, the API fills the originURL if there is no domain in the cookie string and gives you a valid Cookie. Also, there are many other attributes which will be automaticlly set if the server sends them. By far this is the best method in my experience to construct a cookie.

How to store a Cookie?

In the above section we looked at the creation/construction of a cookie. Now lets look at how to store and make use of this Cookie. NSHTTPCookieStorage is our friend. This is a centralised storage for the cookies.

The most interesting and useful feature of this class is that OS (iOS) puts the cookie in the network requests automatically, provided there is a domain match between the cookie and the URL of the request. Suppose the cookie has a domain “.example.com” and the URL of the request is?www.test.example.com,?then the cookie is added in the request automatically without any extra code.

You can also access this cookie and set it o WKWebview request as well. Although SFSafariViewController is stricter and does not share cookies with the app, rest all kinds of network requests (NSURLSession, WKWebView etc.) can carry the Cookie.

For all the NSURLSession requests the cookie is set in the request, if the domain matches the URL of the request. For webview one can add the cookie by accessing it from the storage for initial load like below:

NSURLRequest* request; //your request

[request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies]];

[request HTTPShouldHandleCookies];

How to Verify?

If you are loading a webview and already have a cookie stored, you may have to add the cookie to the initial request. After that load the webview and hit a URL with the same domain as of the cookie. Open Safari WebInspector and see the Request Headers having Cookie.

Generally you can use a fiddler or any network capture tools to look at the request and check for the cookie.

In conclusion, you can handle cookies using these two classes NSHTTPCookie and NSHTTPCookieStorage and having a basic understanding of the cookie and its attributes. Cookies follow the standards defined in RFC 6265 and 2109 and each property has some signifigance.

In the above post I tried to share my experience and the result of my exploration and some trail and error tests with Cookie. Please share and add if you have any additional information.

Credits?:?I enjoyed working on this (for a requirement) and gained some understanding of Cookies in iOS. I would like to thank my team members, Pushpa for having all the discussions and ensuring we did the right thing in the end and Mujeeb for brain storming and testing this feature.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市掠拳,隨后出現(xiàn)的幾起案子怪瓶,更是在濱河造成了極大的恐慌,老刑警劉巖端逼,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異污淋,居然都是意外死亡顶滩,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門(mén)寸爆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)礁鲁,“玉大人,你說(shuō)我怎么就攤上這事赁豆〗龃迹” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵歌憨,是天一觀的道長(zhǎng)着憨。 經(jīng)常有香客問(wèn)我,道長(zhǎng)务嫡,這世上最難降的妖魔是什么甲抖? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮心铃,結(jié)果婚禮上准谚,老公的妹妹穿的比我還像新娘。我一直安慰自己去扣,他們只是感情好柱衔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布樊破。 她就那樣靜靜地躺著,像睡著了一般唆铐。 火紅的嫁衣襯著肌膚如雪哲戚。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,763評(píng)論 1 307
  • 那天艾岂,我揣著相機(jī)與錄音顺少,去河邊找鬼。 笑死王浴,一個(gè)胖子當(dāng)著我的面吹牛脆炎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播氓辣,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼秒裕,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了钞啸?” 一聲冷哼從身側(cè)響起几蜻,我...
    開(kāi)封第一講書(shū)人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎爽撒,沒(méi)想到半個(gè)月后入蛆,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體响蓉,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡硕勿,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了枫甲。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片源武。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖想幻,靈堂內(nèi)的尸體忽然破棺而出粱栖,到底是詐尸還是另有隱情,我是刑警寧澤脏毯,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布闹究,位于F島的核電站,受9級(jí)特大地震影響食店,放射性物質(zhì)發(fā)生泄漏渣淤。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一吉嫩、第九天 我趴在偏房一處隱蔽的房頂上張望价认。 院中可真熱鬧,春花似錦自娩、人聲如沸用踩。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)脐彩。三九已至碎乃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間惠奸,已是汗流浹背荠锭。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留晨川,地道東北人证九。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像共虑,于是被迫代替她去往敵國(guó)和親愧怜。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容