Search code examples
iosobjective-cnsurlsessionnsurl

POST request iOS: what's happening under the hood?


I'm facing a really strange issue and I hope somebody can help me understand where is the problem on which I'm stuck since three days ago.

In simple I make a NSMutableRequest to a simple endpoint where I send (using POST) a json and I'm supposed to receive a response 0 or 1.

The code works the first time the app is run on the device, but somehow it does not work anymore the following times.

To explain myself better, if I uninstall and reinstall the app every time, I get the correct response, but if I run the code twice the second time I get something like [CSRF verification failed] from the endpoint. This error means that I'm not sending the correct format ( or I'm sending something strange).

My question is: how is that possible? Is it possible that I'm sending something else?

The endpoint works correctly because with the android version I don't have any problems...

The code is the following, hope somebody can explain me what is happening under the hood and how I can manage to solve this problem.

    NSString *mail       = [profile valueForKey:@"email"];
NSString *provider   = [profile valueForKey:@"provider"];

// making a GET request to endpoint
NSString *baseUrl = ENDPOINT_URL;

NSString *targetUrl = [NSString stringWithFormat:@"%@", baseUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSString *body = [NSString stringWithFormat:@"{\"mail\":\"%@\", \"provider\":\"%@\"}",mail,provider];
NSData *postData=[body dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
[request setURL:[NSURL URLWithString:targetUrl]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];


[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
  ^(NSData * _Nullable data,
    NSURLResponse * _Nullable response,
    NSError * _Nullable error) {
      if (data){
          NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
          NSLog(@"Data received: %@", myString);
          if ([myString isEqualToString:@"[\"CSRF validation failed\"]"]){
              NSLog(@"ENDPOINT ERROR");
              dispatch_async(dispatch_get_main_queue(), ^{
                  [(AppDelegate *)[[UIApplication sharedApplication] delegate] loginAborted];});

          } else {
              NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
              NSLog(@"Data received: %@", json);
              NSNumber *value = [NSNumber numberWithInt:[[json objectForKey:@"profile_exists"] intValue]];
              if ([value intValue] == 1){
                  //Profile exists.
                  NSLog(@"Profile exists.");
                  [self silentLogin:profile];
              } else if ([value intValue] == 0) {
                  //Profile does not exists.
                  NSLog(@"Profile does not exist.");
                  [self silentRegistration:profile];

              }
              else {
                  //Error.
                  NSLog(@"Error in ENDPOINT VALUE");
                  dispatch_async(dispatch_get_main_queue(), ^{
                  [(AppDelegate *)[[UIApplication sharedApplication] delegate] loginAborted];});
              }
              NSLog(@"%@",json);
          }
      } else {
          NSLog(@"No Data received");
          dispatch_async(dispatch_get_main_queue(), ^{
          [(AppDelegate *)[[UIApplication sharedApplication] delegate] loginAborted];});
      }
  }] resume];

Solution

  • I was able to solve the problem deleting the cookies every time I make a request. It seems that these cookies are re sent every time.

    + (void)clearCookiesForURL: (NSString *)url {
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [cookieStorage cookiesForURL:[NSURL URLWithString:url]];
    for (NSHTTPCookie *cookie in cookies) {
        NSLog(@"Deleting cookie for domain: %@", [cookie domain]);
        [cookieStorage deleteCookie:cookie];
    }
    

    }