全部产品
存储与CDN 数据库 安全 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网 钉钉智能硬件
HTTPDNS
  • HTTPDNS > 
  • 最佳实践 > 
  • iOS WebView 中的 Cookie 处理业务场景“IP直连”方案说明

iOS WebView 中的 Cookie 处理业务场景“IP直连”方案说明

更新时间:2017-11-15 16:45:09

WebView 中的 Cookie 处理业务场景“IP直连”方案说明

概述

本文将讨论下类似这样的问题:

  • WKWebView 对于 Cookie 的管理一直是它的短板,那么 iOS11 是否有改进,如果有,如何利用这样的改进?
    • 采用 IP 直连方案后,服务端返回的 Cookie 里的 Domain 字段也会使用 IP 。如果 IP 是动态的,就有可能导致一些问题:由于许多 H5 业务都依赖于 Cookie 作登录态校验,而 WKWebView 上请求不会自动携带 Cookie。

iOS11推出了新的 API WKHTTPCookieStore 可以用来拦截 WKWebView 的 Cookie 信息

用法示例如下:

  1. WKHTTPCookieStore *cookieStroe = self.webView.configuration.websiteDataStore.httpCookieStore;
  2. //get cookies
  3. [cookieStroe getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) {
  4. NSLog(@"All cookies %@",cookies);
  5. }];
  6. //set cookie
  7. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  8. dict[NSHTTPCookieName] = @"userid";
  9. dict[NSHTTPCookieValue] = @"123";
  10. dict[NSHTTPCookieDomain] = @"xxxx.com";
  11. dict[NSHTTPCookiePath] = @"/";
  12. NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dict];
  13. [cookieStroe setCookie:cookie completionHandler:^{
  14. NSLog(@"set cookie");
  15. }];
  16. //delete cookie
  17. [cookieStroe deleteCookie:cookie completionHandler:^{
  18. NSLog(@"delete cookie");
  19. }];

问题说明:由于许多 H5 业务都依赖于 Cookie 作登录态校验,而 WKWebView 上请求不会自动携带 Cookie。比如,如果你在Native层面做了登陆操作,获取了Cookie信息,也使用 NSHTTPCookieStorage 存到了本地,但是使用 WKWebView 打开对应网页时,网页依然处于未登陆状态。如果是登陆也在 WebView 里做的,就不会有这个问题。

iOS11 的 API 可以解决该问题,只要是存在 WKHTTPCookieStore 里的 cookie,WKWebView 每次请求都会携带,存在 NSHTTPCookieStorage 的cookie,并不会每次都携带。于是会发生首次 WKWebView 请求不携带 Cookie 的问题。

解决方法:

在执行 -[WKWebView loadReques:] 前将 NSHTTPCookieStorage 中的内容复制到 WKHTTPCookieStore 中,以此来达到 WKWebView Cookie 注入的目的。示例代码如下:

  1. [self copyNSHTTPCookieStorageToWKHTTPCookieStoreWithCompletionHandler:^{
  2. NSURL *url = [NSURL URLWithString:@"https://www.v2ex.com"];
  3. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  4. [_webView loadRequest:request];
  5. }];
  1. - (void)copyNSHTTPCookieStorageToWKHTTPCookieStoreWithCompletionHandler:(nullable void (^)())theCompletionHandler; {
  2. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
  3. WKHTTPCookieStore *cookieStroe = self.webView.configuration.websiteDataStore.httpCookieStore;
  4. if (cookies.count == 0) {
  5. !theCompletionHandler ?: theCompletionHandler();
  6. return;
  7. }
  8. for (NSHTTPCookie *cookie in cookies) {
  9. [cookieStroe setCookie:cookie completionHandler:^{
  10. if ([[cookies lastObject] isEqual:cookie]) {
  11. !theCompletionHandler ?: theCompletionHandler();
  12. return;
  13. }
  14. }];
  15. }
  16. }

这个是 iOS11 的API,针对iOS11之前的系统,需要另外处理。

通过让所有 WKWebView 共享同一个 WKProcessPool 实例,可以实现多个 WKWebView 之间共享 Cookie(session Cookie and persistent Cookie)数据。不过 WKWebView WKProcessPool 实例在 app 杀进程重启后会被重置,导致 WKProcessPool 中的 Cookie、session Cookie 数据丢失,目前也无法实现 WKProcessPool 实例本地化保存。可以采取 cookie 放入 Header 的方法来做。

  1. WKWebView * webView = [WKWebView new];
  2. NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx.com/login"]];
  3. [request addValue:@"skey=skeyValue" forHTTPHeaderField:@"Cookie"];
  4. [webView loadRequest:request];

其中对于 skey=skeyValue 这个cookie值的获取,也可以统一通过domain获取,获取的方法,可以参照下面的工具类:

  1. HTTPDNSCookieManager.h
  2. #ifndef HTTPDNSCookieManager_h
  3. #define HTTPDNSCookieManager_h
  4. // URL匹配Cookie规则
  5. typedef BOOL (^HTTPDNSCookieFilter)(NSHTTPCookie *, NSURL *);
  6. @interface HTTPDNSCookieManager : NSObject
  7. + (instancetype)sharedInstance;
  8. /**
  9. 指定URL匹配Cookie策略
  10. @param filter 匹配器
  11. */
  12. - (void)setCookieFilter:(HTTPDNSCookieFilter)filter;
  13. /**
  14. 处理HTTP Reponse携带的Cookie并存储
  15. @param headerFields HTTP Header Fields
  16. @param URL 根据匹配策略获取查找URL关联的Cookie
  17. @return 返回添加到存储的Cookie
  18. */
  19. - (NSArray<NSHTTPCookie *> *)handleHeaderFields:(NSDictionary *)headerFields forURL:(NSURL *)URL;
  20. /**
  21. 匹配本地Cookie存储,获取对应URL的request cookie字符串
  22. @param URL 根据匹配策略指定查找URL关联的Cookie
  23. @return 返回对应URL的request Cookie字符串
  24. */
  25. - (NSString *)getRequestCookieHeaderForURL:(NSURL *)URL;
  26. /**
  27. 删除存储cookie
  28. @param URL 根据匹配策略查找URL关联的cookie
  29. @return 返回成功删除cookie数
  30. */
  31. - (NSInteger)deleteCookieForURL:(NSURL *)URL;
  32. @end
  33. #endif /* HTTPDNSCookieManager_h */
  34. HTTPDNSCookieManager.m
  35. #import <Foundation/Foundation.h>
  36. #import "HTTPDNSCookieManager.h"
  37. @implementation HTTPDNSCookieManager
  38. {
  39. HTTPDNSCookieFilter cookieFilter;
  40. }
  41. - (instancetype)init {
  42. if (self = [super init]) {
  43. /**
  44. 此处设置的Cookie和URL匹配策略比较简单,检查URL.host是否包含Cookie的domain字段
  45. 通过调用setCookieFilter接口设定Cookie匹配策略,
  46. 比如可以设定Cookie的domain字段和URL.host的后缀匹配 | URL是否符合Cookie的path设定
  47. 细节匹配规则可参考RFC 2965 3.3节
  48. */
  49. cookieFilter = ^BOOL(NSHTTPCookie *cookie, NSURL *URL) {
  50. if ([URL.host containsString:cookie.domain]) {
  51. return YES;
  52. }
  53. return NO;
  54. };
  55. }
  56. return self;
  57. }
  58. + (instancetype)sharedInstance {
  59. static id singletonInstance = nil;
  60. static dispatch_once_t onceToken;
  61. dispatch_once(&onceToken, ^{
  62. if (!singletonInstance) {
  63. singletonInstance = [[super allocWithZone:NULL] init];
  64. }
  65. });
  66. return singletonInstance;
  67. }
  68. + (id)allocWithZone:(struct _NSZone *)zone {
  69. return [self sharedInstance];
  70. }
  71. - (id)copyWithZone:(struct _NSZone *)zone {
  72. return self;
  73. }
  74. - (void)setCookieFilter:(HTTPDNSCookieFilter)filter {
  75. if (filter != nil) {
  76. cookieFilter = filter;
  77. }
  78. }
  79. - (NSArray<NSHTTPCookie *> *)handleHeaderFields:(NSDictionary *)headerFields forURL:(NSURL *)URL {
  80. NSArray *cookieArray = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields forURL:URL];
  81. if (cookieArray != nil) {
  82. NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  83. for (NSHTTPCookie *cookie in cookieArray) {
  84. if (cookieFilter(cookie, URL)) {
  85. NSLog(@"Add a cookie: %@", cookie);
  86. [cookieStorage setCookie:cookie];
  87. }
  88. }
  89. }
  90. return cookieArray;
  91. }
  92. - (NSString *)getRequestCookieHeaderForURL:(NSURL *)URL {
  93. NSArray *cookieArray = [self searchAppropriateCookies:URL];
  94. if (cookieArray != nil && cookieArray.count > 0) {
  95. NSDictionary *cookieDic = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
  96. if ([cookieDic objectForKey:@"Cookie"]) {
  97. return cookieDic[@"Cookie"];
  98. }
  99. }
  100. return nil;
  101. }
  102. - (NSArray *)searchAppropriateCookies:(NSURL *)URL {
  103. NSMutableArray *cookieArray = [NSMutableArray array];
  104. NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  105. for (NSHTTPCookie *cookie in [cookieStorage cookies]) {
  106. if (cookieFilter(cookie, URL)) {
  107. NSLog(@"Search an appropriate cookie: %@", cookie);
  108. [cookieArray addObject:cookie];
  109. }
  110. }
  111. return cookieArray;
  112. }
  113. - (NSInteger)deleteCookieForURL:(NSURL *)URL {
  114. int delCount = 0;
  115. NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  116. for (NSHTTPCookie *cookie in [cookieStorage cookies]) {
  117. if (cookieFilter(cookie, URL)) {
  118. NSLog(@"Delete a cookie: %@", cookie);
  119. [cookieStorage deleteCookie:cookie];
  120. delCount++;
  121. }
  122. }
  123. return delCount;
  124. }
  125. @end

使用方法示例:

发送请求

  1. WKWebView * webView = [WKWebView new];
  2. NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxx.com/login"]];
  3. NSString *value = [[HTTPDNSCookieManager sharedInstance] getRequestCookieHeaderForURL:url];
  4. [request setValue:value forHTTPHeaderField:@"Cookie"];
  5. [webView loadRequest:request];

接收处理请求:

  1. NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  2. if (!error) {
  3. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  4. // 解析 HTTP Response Header,存储cookie
  5. [[HTTPDNSCookieManager sharedInstance] handleHeaderFields:[httpResponse allHeaderFields] forURL:url];
  6. }
  7. }];
  8. [task resume];

通过 document.cookie 设置 Cookie 解决后续页面(同域)Ajax、iframe 请求的 Cookie 问题;

  1. WKUserContentController* userContentController = [WKUserContentController new];
  2. WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: @"document.cookie = 'skey=skeyValue';" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
  3. [userContentController addUserScript:cookieScript];

关于COOKIE失效的问题,假如客户端登录 session 存在 COOKIE,此时这个域名配置了多个IP,使用域名访问会读对应域名的COOKIE,使用IP访问则去读对应IP的COOKIE,假如前后两次使用同一个域名配置的不同IP访问,会导致COOKIE的登录session失效,

如果APP里面的webview页面需要用到系统COOKIE存的登录session,之前APP所有本地网络请求使用域名访问,是可以共用COOKIE的登录session的,但现在本地网络请求使用httpdns后改用IP访问,导致还使用域名访问的webview读不到系统COOKIE存的登录session了(系统COOKIE对应IP了)。IP直连后,服务端返回Cookie包含动态 IP 导致登陆失效。

使用IP访问后,服务端返回的cookie也是IP。导致可能使用对应的域名访问,无法使用本地cookie,或者使用隶属于同一个域名的不同IP去访问,cookie也对不上,导致登陆失效,是吧。

我这边的思路是这样的,

  • 应该得干预cookie的存储,基于域名。
  • 根源上,api域名返回单IP

第二种思路将失去DNS调度特性,故不考虑。第一种思路更为可行。

当每次服务端返回cookie后,在存储前都进行下改造,使用域名替换下IP。之后虽然每次网络请求都是使用IP访问,但是host我们都手动改为了域名,这样本地存储的 cookie 也就能对得上了。

代码演示:

在网络请求成功后,或者加载网页成功后,主动将本地的 domain 字段为 IP 的 Cookie 替换 IP 为 host 域名地址。

  1. - (void)updateWKHTTPCookieStoreDomainFromIP:(NSString *)IP toHost:(NSString *)host {
  2. WKHTTPCookieStore *cookieStroe = self.webView.configuration.websiteDataStore.httpCookieStore;
  3. [cookieStroe getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) {
  4. [[cookies copy] enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull cookie, NSUInteger idx, BOOL * _Nonnull stop) {
  5. if ([cookie.domain isEqualToString:IP]) {
  6. NSMutableDictionary<NSHTTPCookiePropertyKey, id> *dict = [NSMutableDictionary dictionaryWithDictionary:cookie.properties];
  7. dict[NSHTTPCookieDomain] = host;
  8. NSHTTPCookie *newCookie = [NSHTTPCookie cookieWithProperties:[dict copy]];
  9. [cookieStroe setCookie:newCookie completionHandler:^{
  10. [self logCookies];
  11. [cookieStroe deleteCookie:cookie
  12. completionHandler:^{
  13. [self logCookies];
  14. }];
  15. }];
  16. }
  17. }];
  18. }];
  19. }

iOS11中也提供了对应的 API 供我们来处理替换 Cookie 的时机,那就是下面的API:

  1. @protocol WKHTTPCookieStoreObserver <NSObject>
  2. @optional
  3. - (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore;
  4. @end
  1. //WKHTTPCookieStore
  2. /*! @abstract Adds a WKHTTPCookieStoreObserver object with the cookie store.
  3. @param observer The observer object to add.
  4. @discussion The observer is not retained by the receiver. It is your responsibility
  5. to unregister the observer before it becomes invalid.
  6. */
  7. - (void)addObserver:(id<WKHTTPCookieStoreObserver>)observer;
  8. /*! @abstract Removes a WKHTTPCookieStoreObserver object from the cookie store.
  9. @param observer The observer to remove.
  10. */
  11. - (void)removeObserver:(id<WKHTTPCookieStoreObserver>)observer;

用法如下:

  1. @interface WebViewController ()<WKHTTPCookieStoreObserver>
  2. - (void)viewDidLoad {
  3. [super viewDidLoad];
  4. [NSURLProtocol registerClass:[WebViewURLProtocol class]];
  5. NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  6. [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
  7. WKHTTPCookieStore *cookieStroe = self.webView.configuration.websiteDataStore.httpCookieStore;
  8. [cookieStroe addObserver:self];
  9. [self.view addSubview:self.webView];
  10. //... ...
  11. }
  12. #pragma mark -
  13. #pragma mark - WKHTTPCookieStoreObserver Delegate Method
  14. - (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore {
  15. [self updateWKHTTPCookieStoreDomainFromIP:CYLIP toHost:CYLHOST];
  16. }

-updateWKHTTPCookieStoreDomainFromIP 方法的实现,在上文已经给出。

这个方案需要客户端维护一个IP —> HOST的映射关系,需要能从 IP 反向查找到 HOST,这个维护成本还时挺高的。下面介绍下,更通用的方法,也是iOS11 之前的处理方法:

步骤:做 IP 替换时将原始 URL 保存到 Header 中

  1. + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
  2. NSMutableURLRequest *mutableReq = [request mutableCopy];
  3. NSString *originalUrl = mutableReq.URL.absoluteString;
  4. NSURL *url = [NSURL URLWithString:originalUrl];
  5. // 异步接口获取IP地址
  6. NSString *ip = [[HttpDnsService sharedInstance] getIpByHostAsync:url.host];
  7. if (ip) {
  8. NSRange hostFirstRange = [originalUrl rangeOfString:url.host];
  9. if (NSNotFound != hostFirstRange.location) {
  10. NSString *newUrl = [originalUrl stringByReplacingCharactersInRange:hostFirstRange withString:ip];
  11. mutableReq.URL = [NSURL URLWithString:newUrl];
  12. [mutableReq setValue:url.host forHTTPHeaderField:@"host"];
  13. // 添加originalUrl保存原始URL
  14. [mutableReq addValue:originalUrl forHTTPHeaderField:@"originalUrl"];
  15. }
  16. }
  17. NSURLRequest *postRequestIncludeBody = [mutableReq cyl_getPostRequestIncludeBody];
  18. return postRequestIncludeBody;
  19. }

然后获取到数据后,手动管理 Cookie:

  1. - (void)handleCookiesFromResponse:(NSURLResponse *)response {
  2. NSString *originalURLString = [self.request valueForHTTPHeaderField:@"originalUrl"];
  3. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  4. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  5. NSDictionary<NSString *, NSString *> *allHeaderFields = httpResponse.allHeaderFields;
  6. if (originalURLString && originalURLString.length > 0) {
  7. NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:allHeaderFields forURL: [[NSURL alloc] initWithString:originalURLString]];
  8. if (cookies && cookies.count > 0) {
  9. NSURL *originalURL = [NSURL URLWithString:originalURLString];
  10. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:originalURL mainDocumentURL:nil];
  11. }
  12. }
  13. }
  14. }
  15. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)newRequest completionHandler:(void (^)(NSURLRequest *))completionHandler {
  16. NSString *location = response.allHeaderFields[@"Location"];
  17. NSURL *url = [[NSURL alloc] initWithString:location];
  18. NSMutableURLRequest *mRequest = [newRequest mutableCopy];
  19. mRequest.URL = url;
  20. if (location && location.length > 0) {
  21. if ([[newRequest.HTTPMethod lowercaseString] isEqualToString:@"post"]) {
  22. // POST重定向为GET
  23. mRequest.HTTPMethod = @"GET";
  24. mRequest.HTTPBody = nil;
  25. }
  26. [mRequest setValue:nil forHTTPHeaderField:@"host"];
  27. // 在这里为 request 添加 cookie 信息。
  28. [self handleCookiesFromResponse:response];
  29. [XXXURLProtocol removePropertyForKey:XXXURLProtocolHandledKey inRequest:mRequest];
  30. completionHandler(mRequest);
  31. } else{
  32. completionHandler(mRequest);
  33. }
  34. }

发送请求前,向请求中添加Cookie信息:

  1. + (void)handleCookieWithRequest:(NSMutableURLRequest *)request {
  2. NSString* originalURLString = [request valueForHTTPHeaderField:@"originalUrl"];
  3. if (!originalURLString || originalURLString.length == 0) {
  4. return;
  5. }
  6. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
  7. if (cookies && cookies.count >0) {
  8. NSDictionary *cookieHeaders = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
  9. NSString *cookieString = [cookieHeaders objectForKey:@"Cookie"];
  10. [request addValue:cookieString forHTTPHeaderField:@"Cookie"];
  11. }
  12. }
  13. + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
  14. NSMutableURLRequest *mutableReq = [request mutableCopy];
  15. //...
  16. [self handleCookieWithRequest:mutableReq];
  17. return [mutableReq copy];
  18. }

相关的文章:

本文导读目录