UPDATE: My buddy Carlos created an updated article that shows how to use the replacement for ServiceFilters in managed clients, check it out: Caching and handling expired tokens in azure mobile services managed SDK
On day 8 we looked at how you can generate your own Mobile Services JWT tokens to create a custom identity. One thing you may have noticed is that the JWT has an expiry, meaning that at some point the user’s authentication token will become invalid. In day 10’s post we also looked at an approach that would allow you to cache the user’s token to save them logging in repeatedly. However, the combination of an expiry and a cached token have an obvious downfall – what happens when it expires? Well, you have to log your user back in, obviously.
So you need to be ready to receive a 401 unauthorized response and log the user back in. But, you probably don’t want to write this code every time you call Mobile Services, right? Enter filters which we covered in Day 3. Filters allow me to intercept calls to and responses from the Mobile Service for any given client instance. This will allow us to inspect the response for a 401 response, trigger the login flow and then, best of all, automatically replay the request that was rejected with a 401.
Here’s the code for C# / Windows 8:
As you can see, all this filter does is inspect the response for a 401 status code. If the call was unauthorized, we log the user in again and then attach the new authentication token to the original request (by modifying the header). Resend the request and then send the response back to the consuming code, as though nothing happened!
You can also do this on iOS / Objective C:
The iOS implementation assumes it’s safe to grab the current rootViewController (from the current UIApplication delegate’s window). This may not be the case for your application. In reality, you’d probably want to take this concept and use it to trigger your logout/login presentation (e.g. via NSNotificationCenter). I’ll leave this as an exercise for the reader as it is likely to vary by application.
From now on, I’ll be using this in all applications as my primary login flow as it composes extremely well with cached credentials. Join us again tomorrow for the last day of the twelve days of ZUMO.