如何以Xamarin形式从Microsoft注销?

时间:2019-06-18 07:53:29

标签: authentication xamarin xamarin.forms xamarin.android forms-authentication

我正在研究xamarin形式。使用 AuthenticationContext 通过Microsoft登录。单击登录按钮后,它将重定向到Microsoft登录页面。登录工作正常。当我从用户的注销按钮登录后,单击用户应该注销,如何注销无按钮单击?

使用以下代码我可以登录

public Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
    {
        try
        {
            var authContext = new AuthenticationContext(authority);
            if (authContext.TokenCache.ReadItems().Any())
            {
                authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
            }


            var uri = new Uri(returnUri);
            var platformParams = new PlatformParameters((Activity)Forms.Context);
            var authResult = authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
            return authResult;
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex);
            return null;
        }
    }

请帮助我如何注销?

2 个答案:

答案 0 :(得分:2)

通过清除令牌缓存Logout,然后退出应用程序,或将应用程序主页面设置为登录页面。

对于iOS:

public async Task LogoutAsync()
        {
            var authContext = new AuthenticationContext(authority);
            if (authContext.TokenCache.ReadItems().Any())
            {
                authContext.TokenCache.Clear();
            }

            //In addition to clearing the token cache, you should also clear the cookies in the web view.
            //Otherwise, the session cookies come into play and that is why you are seeing the web view come up and disappear immediately.
            foreach (var cookie in NSHttpCookieStorage.SharedStorage.Cookies)
            {
                NSHttpCookieStorage.SharedStorage.DeleteCookie(cookie);
            }
        }

与Android相同,只是清除Cookie的另一种方法:

        CookieManager.Instance.RemoveAllCookie();

答案 1 :(得分:2)

清除访问令牌以退出登录

Public static void Logout()
{
  AuthenticationContext authContext = new 
  AuthenticationContext(AuthenticationConstants.Authority);
  TokenCache tokenCache = ac.TokenCache;
  tokenCache.Clear();
}

在返回登录页面之前调用此方法。我的意思是,在导航回到登录页面之前,您必须清除访问令牌

Like example
private void NavigateToLoginViewController()
{ 
    // call the above logout method here 
   .
   .
   .
}