1

I have drupal webservice to post(save) an item through objective c. I googled and found that I need to set cookie for that. So i did the following:

NSURL *url = [[NSURL alloc] initWithString:@"http://lanetteam.net/kaleio/services/session/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString* csrf;
csrf = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSString *str = [NSString stringWithFormat:@"http://lanetteam.net/kaleio/node?title=%@&body[und][0][value]=%@",_txtTitle.text,txtContent.text];

NSURL *url1 = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request1= [[NSMutableURLRequest alloc] initWithURL:url1];
NSURLResponse *response1 = nil;
[request1 setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request1 addValue:csrf forHTTPHeaderField:@"X-CSRFToken"];

NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Cookie", NSHTTPCookieName,
                            [NSString stringWithFormat:@"%@=%@", [appDelegate.dictUserProfile valueForKey:@"session_name"],[appDelegate.dictUserProfile valueForKey:@"sessionid"]], NSHTTPCookieValue,
                            nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties]; //**error here, cookie is returned as nil**

NSArray* cookies = [NSArray arrayWithObjects: cookie, nil];



NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];


[request1 setAllHTTPHeaderFields:headers];

NSData *responseData1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response1 error:nil];

NSMutableArray *jsonArray=[NSJSONSerialization JSONObjectWithData:responseData1 options:NSJSONReadingMutableContainers error:nil];

NSLog(@"data : %@", jsonArray);

i have mentioned above where the error occurs. Please let me know how do i solve this, i have been trying this since last many days. Without setting cookie, i get the following error :

CSRF validation failed
z22
  • 10,013
  • 17
  • 70
  • 126

2 Answers2

2

I am suffer also same problem.After setting a token I am geeting error CSRF validation failed.But i am got solution I think its not appropriate before call any webservices. call logout services it worked for me

VARUN SINGHAL
  • 373
  • 1
  • 14
0

You need to get the X-CSRF-Token and put it in your header.

After logging in, you can get the token from a browser by going to: http://yoursite.com/services/session/token

Then, put the token in the header of all your requests:

X-CSRF-Token=<token>

See also: How to get CSRF token in iOS?

Community
  • 1
  • 1