Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Active Directory Logout with ADAL library

I used the my Azure Active Directory to protect my web API and I create a native application in the Azure management portal. This native application is basically a MVC web application and I use the ADAL library to get the token and call the api with that token. The code I used to get the token is shown below:

AuthenticationContext ac = new AuthenticationContext(authority);
AuthenticationResult ar = ac.AcquireToken(resourceID, clientID, redirectURI);
string accessToken = ar.AccessToken;

Now I need to logout and switch to another user but somehow the user credentials are remembered by the system. I clear the token cache in the authentication context and post logout api request as follows where *** is my tenant ID.

//Log out after api call
ac.TokenCache.Clear();

string requestUrl = "https://login.windows.net/***/oauth2/logout";

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
var response = await client.SendAsync(request);

The api call succeeds but the logout doesn't work. What should I do to logout and switch to another user?

like image 332
de li Avatar asked Aug 24 '15 00:08

de li


3 Answers

I don't think this would work. You would need to redirect the user to logout URL for logout to work.

Here's how you can create a logout URI:

https://login.microsoftonline.com/{0}/oauth2/logout?post_logout_redirect_uri={1}

Where:

  • {0} - Fully qualified name of your Azure Active Directory e.g. yourad.onmicrosoft.com or tenant id.
  • {1} - The URL of your application where a user must be redirected back after the logout is complete. This should be properly URL encoded.
like image 127
Gaurav Mantri Avatar answered Oct 13 '22 02:10

Gaurav Mantri


If you goal is to sign in a s a different user, you don't strictly need to log out the first user from its session with Azure AD. You can pass PrompBehavior.Always in your AcquireToken call, so that you will be guaranteed to prompt the user with a clean credential gathering UX. Note: if you want to wipe every trace of the first user from the app you can keep the cache cleanup code you have. ADAL allows you to keep tokens for multiple users tho, hence if your app as multi-user functions this might be useful - the catch is that if you do so, at every AcquireToken you'll have to also specify which user you want a token for or ADAL won't know which one to return. If you don't need multiple users at once, the cache cleanup + PromptBehavior.Always remains the easiest path.

like image 37
vibronet Avatar answered Oct 13 '22 00:10

vibronet


You can do this for clear cache :

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        mAuthContext.getCache().removeAll();
like image 35
M.Eqbalazar Avatar answered Oct 13 '22 00:10

M.Eqbalazar