Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically handle token refreshing with RestKit

I have a project which you can imagine is like the Facebook app and I'm having trouble grasping how to organize it with RestKit and handle tokens since I'm a RestKit beginner.

This is what I got so far:

  • Core Data NSManagedObject classes, for each of them I added a category called REST that has functions to provide RKObjectMapping and RKRouteSet
  • custom RKObjectManager subclass which handles setting up headers, MIME types, setting authorization headers and Core Data stores
  • RKObjectRequestOperation subclass

If you have organizational advice shoot, but my main question is how do I implement automatic token refreshing after recieving a 401 HTTP status code and firing the failed request again with a fresh token?

I started by overriding the metod in my RKObjectRequestOperation subclass:

- (void)setCompletionBlockWithSuccess:(void ( ^ ) ( RKObjectRequestOperation *operation , RKMappingResult *mappingResult ))success failure:(void ( ^ ) ( RKObjectRequestOperation *operation , NSError *error ))failure

So now I can intercept a 401 response, but now I have to make another call to refresh the token and then re-enqueue the failed operation with a fresh token, please advise how to do that.

like image 553
Sasha_K Avatar asked Oct 21 '22 08:10

Sasha_K


1 Answers

I generally wouldn't use a custom RKObjectRequestOperation if you are using an object manager. I'd handle it at the object manager level.

In the object manager you can override each of the main request methods (which are supplied with success and failure blocks). You can implement these methods to call super but substituting the success and failure blocks with new versions which add some logic before calling the supplied versions.

Now, the additional logic would be a check of the response status. If it shows a token refresh is required it can be actioned and then the object manager can trigger a new load, using the parameters supplied in the first request.

Also, you shouldn't re-queue an operation unless the documentation states that it is supported as some operations won't work the second time they're executed...

like image 71
Wain Avatar answered Oct 23 '22 00:10

Wain