Search code examples
azurewindows-runtimewindows-store-appsazure-mobile-servicesazure-active-directory

Azure Active Directory Single Sign On Multiple tokens detected Issue


I have implemented Azure Active Directory in my Windows 8.1 store app.

First time when the app opens it opens the AAD login popup and user will enter email and password then log in to the app, for that I am using the below code it is working fine.

    AADLoginFirstTime()
{

AuthenticationContext ac = new AuthenticationContext(App.authority);
                    AuthenticationResult ar = await ac.AcquireTokenAsync(App.resourceURI, App.clientID, (Uri)null,PromptBehavior.Always);
                    JObject payload = new JObject();
                    payload["access_token"] = ar.AccessToken;
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);

//saving user token into vault
credential = new PasswordCredential(provider,
                            user.UserId, user.MobileServiceAuthenticationToken);
                        vault.Add(credential);

}

From second time onwards I am using calling the below lines of code

    AADLoginSecondTime()

{

AuthenticationContext ac = new AuthenticationContext(App.authority);
                        AuthenticationResult ar = await ac.AcquireTokenAsync(App.resourceURI, App.clientID, (Uri)null);
                        JObject payload = new JObject();
                        payload["access_token"] = ar.AccessToken;
                        user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);

}

The difference is second time onwards the LoginAsync method don't have prompt behaviour.

This is working fine for single user.

For logging out I am just navigating the page to login screen and calling AADLoginFirstTime() method to show the login popup.

When it prompts the login popup if I use another user AAD credentials and logs into the app, from next time opens the app and now calling AADLoginSecondTime() method then the app throws an exception called Mobile service Invalid Token.

AuthenticationResult ar = await ac.AcquireTokenAsync(App.resourceURI, App.clientID, (Uri)null);

This method returns an empty token.

enter image description here

Is this causing because of previous user not loggedout completely from the app? If it is how can I log out previous user completely?


Solution

  • Every time you get a token with ADAL, it will be saved (along with a lot of other stuff) in a persistent cache. If you want to flush that cache, you can call ac.TokenCache.Clear(). If you want to delete tokens for specific users, you can just run a LINQ query against the cache and remove specific items. Note that this is all independent from Mobile Services.