Azure Active Directory Logout with ADAL library

僤鯓⒐⒋嵵緔 提交于 2021-02-07 06:21:31

问题


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?


回答1:


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.



回答2:


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.




回答3:


You can do this for clear cache :

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        mAuthContext.getCache().removeAll();


来源:https://stackoverflow.com/questions/32172898/azure-active-directory-logout-with-adal-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!