Wrapcode

Xamarin and Azure Mobile Service, right way to Log Out.

| 2 min read

It's been more than 4 months since I started working on Xamarin (Android, iOS and Forms). Earlier, I had an opportunity integrating Azure Mobile Services in Xamarin application. We had a requirement where user needed to log out and forced to log in again (weird it was but can't help).

We tried using out of the box method that Azure Mobile Services provide

MobileServiceClient.Logout()
view raw AzureMobileAgent.cs hosted with ❤ by GitHub

And redirect user to the Activity containing Azure Mobile Services MobileServiceClient.LoginAsync(...) method which we used to authenticate user against configured AAD.

My expectation was, this method takes care of logging out and clearing all the leftovers of previous login session. However Logout method only clears MobileServiceUser object which stores MobileServiceAuthenticationToken and UserId which is used as authentication keys for further API calls. And if I redirect to Login activity, it automatically logs in the user again without asking user credentials again.

I wanted user to force login whenever user logs out. Later, I realized, Android app has webkit cache which stores cookies related to AAD login. When app redirects user to login page, webkit reuses the existing cookies and user doesn't have to enter credentials again.

To get over this issue, we just cleared cookies from Webkit cookie manager of app instance..

if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
Android.Webkit.CookieManager.Instance.RemoveAllCookies(null);
else
Android.Webkit.CookieManager.Instance.RemoveAllCookie();
MobileServiceClient.Logout();
view raw RemoveCookies.cs hosted with ❤ by GitHub

Android Lollipop introduces new method public virtual void RemoveAllCookies(IValueCallback callback); which breaks on older SDK versions (sad). That's the reason we are explicitly checking the sdk version and then executing required method to avoid crashes.

That's how you clear everything, not just User object while using Azure Mobile Services with Xamarin. I will sharer iOS code for the same someday.

Peace, RP