iOS Same Ip, Different Ports, Session Invalidation Issue

1. Problem.

The company performs normal login operations on the HTTPS server (port 443) ( https://ip1:443/ ),  Then the data file upload is processed on port 666 ( https://ip1:666/ ).

Server verifies and saves sessions in the cookie after successful login at https://ip1:443/, but then upload file in port 666 (https://ip1:666), and then go back to url https://ip1:443. But after the port 443 is called, the server fails to verify the session and the session timeout problem occurs.

2. Reason.

Because the session state is implemented by the jsessionid stored in the cookie,  therefore, because the session_id, name, domain, and path of both servers are the same, session id is overridden, resulting in session invalidation.

It is also concluded that cookies do not distinguish ports, cookies distinguish only domain, paths, and names.

3. Solution.

Before accessing port 666, cache the cookie to the local, and then re-write the cookie after you return to port 443.

Below is the source code.

Export cookies and cache them

//Get all cookies
NSHTTPCookieStorage* nCookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
// Get a copy of the cookies.
NSArray* nCookies = [nCookies cookiesForURL:[NSURL URLWithString:urlStr]].copy;

// Loop to cache cookie.
for(NSHTTPCookie*cookie in nCookies)
{
   if([cookie isKindOfClass:[NSHTTPCookie class]])
   {
      // If cookie name is JSESSIONID
      if([cookie.name isEqualToString:@"JSESSIONID"])
      {
         // Get cookie related data.
         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;
      }
   }
}

Read cookies and rewrite

-(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];

   }
}
Posted in