背景
公司在https服務(wù)器(端口443)進(jìn)行正常登陸業(yè)務(wù)等處理
https://ip1:443/
然后在端口444服務(wù)器進(jìn)行資料文件上傳等處理
https://ip1:444/
因?yàn)榉?wù)器在https://ip1:443/登陸成功之后對cookie中的session進(jìn)行校驗(yàn)保存讲岁,而一旦出現(xiàn)訪問443->444->443,就是進(jìn)行文件上傳操作后衬以,再調(diào)用443端口后缓艳,服務(wù)器對session校驗(yàn)失敗,出現(xiàn)會話超時(shí)問題
原因
因?yàn)閟ession狀態(tài)是靠cookie中存儲的jsessionid實(shí)現(xiàn)的泄鹏,所以郎任,由于兩個服務(wù)器的sessionid秧耗,名稱备籽、域、路徑都一樣分井,導(dǎo)致sessionid被覆蓋车猬,從而導(dǎo)致session失效;由此也得出cookie是不區(qū)分端口的尺锚。
cookie不區(qū)分端口號
cookie區(qū)分域珠闰、路徑、名稱
處理辦法
在訪問另一個端口前瘫辩,把cookie緩存到本地伏嗜,然后在返回443端口后坛悉,再把cookie重新寫入
導(dǎo)出cookie并緩存:
//導(dǎo)出cookie
NSHTTPCookieStorage* nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* nCookies = [nCookies cookiesForURL:[NSURL URLWithString:urlStr]].copy;
for(NSHTTPCookie*cookie in nCookies)
{
if([cookie isKindOfClass:[NSHTTPCookie class]])
{
if([cookie.name isEqualToString:@"JSESSIONID"])
{
NSNumber*sessionOnly =[NSNumber numberWithBool:cookie.sessionOnly];
NSNumber*isSecure = [NSNumber numberWithBool:cookie.isSecure];
NSArray*cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure,nil];
[[NSUserDefaults standardUserDefaults]setObject:cookies forKey:@"cookies"];
break;
}
}
}
讀取cookie并寫入:
-(void)loadCookies
{
NSArray*cookies =[[NSUserDefaults standardUserDefaults]objectForKey:@"cookies"];
if(cookies.count>0)
{
NSMutableDictionary*cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:[cookies objectAtIndex:0]forKey:NSHTTPCookieName];
[cookieProperties setObject:[cookies objectAtIndex:1]forKey:NSHTTPCookieValue];
[cookieProperties setObject:[cookies objectAtIndex:3]forKey:NSHTTPCookieDomain];
[cookieProperties setObject:[cookies objectAtIndex:4]forKey:NSHTTPCookiePath];
NSHTTPCookie*cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookie:cookieuser];
}
}
PS:AFNetworking也能用相同處理辦法