0

I created a test application (using scaffold) at heroku and I built an iOS client (using AFNetworking 2) to this heroku application. I was trying to delete records from heroku using iOS app and It didn't work. I received 422 status error from server.

Looking at heroku logs I figure out that server is claiming for CSRF token. So I tried to do that with this code on my iOS client:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer = [AFHTTPResponseSerializer new];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];

[manager DELETE:contact.url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Response:  %@", [operation description]) ;
    if (block) {
        block(error);
    }
    NSLog(@"Error: %@", error);
}];

It didn't work.

How can I add CSRF token into http header on AFHTTPRequestOperationManager ?

Sebastian
  • 6,154
  • 5
  • 33
  • 51

2 Answers2

5

Two things here:

  1. If your server is complaining about a lack of a CSRF token, then forging one isn't going to be the correct solution. See this Stack Overflow answer for more information. While you're just starting to get everything up-and-running, you can temporarily disable this by commenting out the protect_from_forgery call in your API controller.
  2. AFHTTPRequestOperationManager is initialized with an AFJSONResponseSerializer already, so you don't need to set that yourself. You can add a default X-XSRF-TOKEN (or whatever header by doing [manager.requestSerializer setValue:@"..." forHTTPHeaderField:@"..."];
Community
  • 1
  • 1
mattt
  • 19,544
  • 7
  • 73
  • 84
0

With AFNetworking2 you customize http headers in request serializer. So you need to subclass the one you currently work with and add this logic there.

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                               withParameters:(NSDictionary *)parameters
                                        error:(NSError *__autoreleasing *)error {
    NSMutableDictionary *modifiedParams = [parameters mutableCopy];
    modifiedParams[@"your-header-name"] = @"you-header-value";

    NSMutableURLRequest *res = [super requestBySerializingRequest:request
                                                   withParameters:modifiedParams
                                                            error:error];
    return res;
}
gavrix
  • 321
  • 2
  • 10