I'm writing a small iOS client for a server protected with OAuth2.
I'm wondering if is it possible using AFOAuth2Manager
[here] auto-refreshing the expired token.
The idea is that the logic for refreshing the client when the server responds with a 401, or raise an error when the refresh method returns a 401 should be quite common, so probably it is integrated in some library.
Swift solution with Alamofire 4.0. Based on RequestAdapter and RequestRetrier protocols: example link
I was searching an answer for this problem and "Matt", the creator of AFNetworking, suggest this:
Simple, but effective?, trying now, will edit with report...
Unfortunately I didn't found any framework for solve this problem so I wrote a short wrapper around
AFNetworking
(if someone is interested I can publish on github) The logic is to execute the request, and in case of http response401
, try to refresh the auth-token and when it's done to re-execute the previous request.I created a subclass of
AFOAuth2Manager
In this subclass I override this method:
calling a custom method with an additional parameter:
checkIfTokenIsExpired
. This is required in order to avoid infinite loops.The implementation of this method is straigth forward: if we don't need to check the token just call the super class.
otherwise we perform the request with a custom failure block
http status code
, if 401 try to automatically re-authorize.AFOAuthManager
to refresh the token.requestByAddingHeadersToRequest:
just copy all the header fields from the previous request.successBlock
andfailureBlock
are the same of the previous request.