背景
公司在https服务器(端口443)进行正常登陆业务等处理
https://ip1:443/
然后在端口444服务器进行资料文件上传等处理
https://ip1:444/
因为服务器在https://ip1:443/登陆成功之后对cookie中的session进行校验保存,而一旦出现访问443->444->443,就是进行文件上传操作后,再调用443端口后,服务器对session校验失败,出现会话超时问题
原因
因为session状态是靠cookie中存储的jsessionid实现的,所以,由于两个服务器的sessionid,名称、域、路径都一样,导致sessionid被覆盖,从而导致session失效;由此也得出cookie是不区分端口的。
cookie不区分端口号
cookie区分域、路径、名称
处理办法
在访问另一个端口前,把cookie缓存到本地,然后在返回443端口后,再把cookie重新写入
导出cookie并缓存:
//导出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也能用相同处理办法
网友评论