38

I have a use case that should be rather common but I can't find an easy way to handle it with AFNetworking:

Whenever the server returns a specific status code for any request, I want to:

  • remove a cached authentication token
  • re-authenticate (which is a separate request)
  • repeat the failed request.

I thought that this could be done via some global completion/error handler in AFHTTPClient, but I didn't find anything useful. So, what's the "right" way to do what I want? Override enqueueHTTPRequestOperation: in my AFHTTPClient subclass, copy the operation and wrap the original completion handler with a block that does what I want (re-authenticate, enqueue copied operation)? Or am I on the wrong track altogether?

Thanks!

EDIT: Removed reference to 401 status code, since that's probably reserved for HTTP basic while I'm using token auth.

Daniel Rinser
  • 8,855
  • 4
  • 41
  • 39

6 Answers6

30

I use an alternative means for doing this with AFNetworking 2.0.

You can subclass dataTaskWithRequest:success:failure: and wrap the passed completion block with some error checking. For example, if you're working with OAuth, you could watch for a 401 error (expiry) and refresh your access token.

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)urlRequest completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))originalCompletionHandler{

    //create a completion block that wraps the original
    void (^authFailBlock)(NSURLResponse *response, id responseObject, NSError *error) = ^(NSURLResponse *response, id responseObject, NSError *error)
    {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        if([httpResponse statusCode] == 401){
            NSLog(@"401 auth error!");
            //since there was an error, call you refresh method and then redo the original task
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

                //call your method for refreshing OAuth tokens.  This is an example:
                [self refreshAccessToken:^(id responseObject) {

                    NSLog(@"response was %@", responseObject);
                    //store your new token

                    //now, queue up and execute the original task               
                    NSURLSessionDataTask *originalTask = [super dataTaskWithRequest:urlRequest completionHandler:originalCompletionHandler];
                    [originalTask resume];
                }];                    
            });
        }else{
            NSLog(@"no auth error");
            originalCompletionHandler(response, responseObject, error);
        }
    };

    NSURLSessionDataTask *task = [super dataTaskWithRequest:urlRequest completionHandler:authFailBlock];

    return task;

}
Sebyddd
  • 4,305
  • 2
  • 39
  • 43
adamup
  • 1,508
  • 19
  • 29
21

In the AFHTTPClient's init method register for the AFNetworkingOperationDidFinishNotification which will be posted after a request finishes.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HTTPOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];

In the notification handler check the status code and copy the AFHTTPRequestOperation or create a new one.

- (void)HTTPOperationDidFinish:(NSNotification *)notification {
  AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)[notification object];

    if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
        return;
    }

    if ([operation.response statusCode] == 401) {
        // enqueue a new request operation here
    }
}

EDIT:

In general you should not need to do that and just handle the authentication with this AFNetworking method:

- (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
Felix
  • 35,354
  • 13
  • 96
  • 143
  • I haven't thought of notifications - much better and less intrusive than customizing enqueueing of requests. Thanks a lot! As to the authentication challenge block: I'm actually using token authentication rather than basic auth, so I guess that won't work, right? Sorry for having you misled by mentioning 401. Bonus question: What would be the correct response code for "invalid token"? 400? – Daniel Rinser Oct 15 '12 at 15:39
  • I'm not sure what the correct response code for "invalid token" is. Maybe 403 is more appropriate. – Felix Oct 15 '12 at 16:05
  • 1
    AFAIK 403 is more for failed *authorization* rather than authentication ("authentication succeeded (if any), but you are not permitted to do this"). But nevermind, that's another question. Thanks again for your help. – Daniel Rinser Oct 15 '12 at 16:09
  • re 403: One could also argue that not providing a token or providing an invalid token causes me to be "anonymous". Thus accessing some protected resource results in an authorization error (403). Will think about it. ;) – Daniel Rinser Oct 15 '12 at 16:20
  • 1
    FYI (for everyone else wondering if you should copy an `AF*Operation` to re-execute it): "`-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations." – Daniel Rinser Oct 15 '12 at 16:28
  • 2
    It seems that my optimism regarding copying the operation was wrong: First, `copy` copies too much stuff (eg. the response). Second, it does not include the original request's completion blocks which is a deal-breaker for me. See my follow-up question: http://stackoverflow.com/questions/12951037/afnetworking-access-to-completion-handlers-when-retrying-operation – Daniel Rinser Oct 18 '12 at 09:16
  • DOH! Your followup comment was hidden behind "Show 1 more comment" so I merrily implemented a solution using copied blocks and then spent an hour debugging. Irritatingly, the PROGRESS block was copied and was executed (leading me to believe that everything was working), but the completion/failure block was not, as you discovered. – Eli Burke Aug 19 '13 at 18:20
4

Here is the Swift implementation of user @adamup 's answer

class SessionManager:AFHTTPSessionManager{
static let sharedInstance = SessionManager()
override func dataTaskWithRequest(request: NSURLRequest!, completionHandler: ((NSURLResponse!, AnyObject!, NSError!) -> Void)!) -> NSURLSessionDataTask! {

    var authFailBlock : (response:NSURLResponse!, responseObject:AnyObject!, error:NSError!) -> Void = {(response:NSURLResponse!, responseObject:AnyObject!, error:NSError!) -> Void in

        var httpResponse = response as! NSHTTPURLResponse

        if httpResponse.statusCode == 401 {
            //println("auth failed")

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), { () -> Void in

                self.refreshToken(){ token -> Void in
                    if let tkn = token{
                        var mutableRequest = request.mutableCopy() as! NSMutableURLRequest
                        mutableRequest.setValue(tkn, forHTTPHeaderField: "Authorization")
                        var newRequest = mutableRequest.copy() as! NSURLRequest
                        var originalTask = super.dataTaskWithRequest(newRequest, completionHandler: completionHandler)
                        originalTask.resume()
                    }else{
                        completionHandler(response,responseObject,error)
                    }

                }
            })
        }
        else{
            //println("no auth error")
            completionHandler(response,responseObject,error)
        }
    }
    var task = super.dataTaskWithRequest(request, completionHandler:authFailBlock )

    return task
}}

where refreshToken (...) is an extension method I wrote to get a new token from the server.

Community
  • 1
  • 1
darthjit
  • 1,555
  • 13
  • 20
2

Took a similar approach, but I couldn't get the status code object with phix23's answer so I needed a different plan of action. AFNetworking 2.0 changed a couple of things.

-(void)networkRequestDidFinish: (NSNotification *) notification
{
    NSError *error = [notification.userInfo objectForKey:AFNetworkingTaskDidCompleteErrorKey];
    NSHTTPURLResponse *httpResponse = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
    if (httpResponse.statusCode == 401){
        NSLog(@"Error was 401");
    }
}
dsrees
  • 6,116
  • 2
  • 26
  • 26
  • Are you able to just put this in the appDelegate or does it need to go into the viewcontroller you called the request in? – Trianna Brannon May 01 '15 at 18:55
  • 1
    @TriannBrannon, you used it to complement the selected answer. Instead of using @selector(HTTPOperationDidFinish:) you use @selector(networkRequestDidFinish:) and instead of AFNetworkingOperationDidFinishNotification you use AFNetworkingTaskDidCompleteNotification. That's how I got it working – Bruno Tereso May 05 '15 at 14:07
0

If you are subclassing AFHTTPSessionManager or using directly an AFURLSessionManager you could use the following method to set a block executed after the completion of a task:

/**
 Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.

 @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
*/
- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block;

Just perform whatever you want to do for each tasks of the session in it:

[self setTaskDidCompleteBlock:^(NSURLSession *session, NSURLSessionTask *task, NSError *error) {
    if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
        if (httpResponse.statusCode == 500) {

        }
     }
}];

EDIT: In fact if you need to handle an error returned in the response object the above method won't do the job. One way if you are subclassing AFHTTPSessionManager could be to subclass and set a custom response serializer with it's responseObjectForResponse:data:error: overloaded like that:

@interface MyJSONResponseSerializer : AFJSONResponseSerializer
@end

@implementation MyJSONResponseSerializer

#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
                           data:(NSData *)data
                          error:(NSError *__autoreleasing *)error
{
    id responseObject = [super responseObjectForResponse:response data:data error:error];

    if ([responseObject isKindOfClass:[NSDictionary class]]
        && /* .. check for status or error fields .. */)
    {
        // Handle error globally here
    }

    return responseObject;
}

@end

and set it in your AFHTTPSessionManager subclass:

@interface MyAPIClient : AFHTTPSessionManager
+ (instancetype)sharedClient;
@end

@implementation MyAPIClient

+ (instancetype)sharedClient {
    static MyAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        _sharedClient = [[MyAPIClient alloc] initWithBaseURL:[NSURL URLWithString:MyAPIBaseURLString]];
        _sharedClient.responseSerializer = [MyJSONResponseSerializer serializer];
    });

    return _sharedClient;
}

@end
Bluezen
  • 850
  • 9
  • 13
0

To ensure that multiple token refreshes are not issued at around the same time, it is beneficial to either queue your network requests and block the queue when the token is refreshing, or add a mutex lock (@synchronized directive) to your token refresh method.

Ryan
  • 3,414
  • 2
  • 27
  • 34
  • can you help with the access token cycle implementation with AFNetworking. We do not want to add authorization header to every request. There must be a neat way to refresh the token (on receiving 401 error) and make the request again. – Utsav Dusad Mar 01 '17 at 14:48