xamarin.forms - AcquireToken 一段时间后停止工作

标签 xamarin.forms azure-active-directory azure-ad-msal

我正在使用 Xamarin 表单应用程序。

我使用下面的代码片段来获取 AAD 登录的 token 。

 IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync().ConfigureAwait(false);
            try
            {
                if (btnSignInSignOut.Text == "Sign in")
                {
                    try
                    {
                        IAccount firstAccount = accounts.FirstOrDefault();
                        authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);
                    }
                    catch (MsalUiRequiredException)
                    {
                        try
                        { 
                            var builder = App.PCA.AcquireTokenInteractive(App.Scopes)
                                                                       .WithParentActivityOrWindow(App.ParentWindow);

                            if (Device.RuntimePlatform != "UWP")
                            {
                                // on Android and iOS, prefer to use the system browser, which does not exist on UWP
                                SystemWebViewOptions systemWebViewOptions = new SystemWebViewOptions()
                                {                            
                                    iOSHidePrivacyPrompt = true,
                                };

                                builder.WithSystemWebViewOptions(systemWebViewOptions);
                                builder.WithUseEmbeddedWebView(false);
                            }

                            authResult = await builder.ExecuteAsync().ConfigureAwait(false);
                        }
                        catch (Exception ex2)
                        {
                            await DisplayAlert("Acquire token interactive failed. See exception message for details: ", ex2.Message, "Dismiss");
                        }
                    }

                    if (authResult != null)
                    {
                        var content = await GetHttpContentWithTokenAsync(authResult.AccessToken);
                        UpdateUserContent(content);
                    }
                }
                else
                {
                    while (accounts.Any())
                    {
                        await App.PCA.RemoveAsync(accounts.FirstOrDefault()).ConfigureAwait(false);
                        accounts = await App.PCA.GetAccountsAsync().ConfigureAwait(false);
                    }

                    
                    Device.BeginInvokeOnMainThread(() => 
                    {
                        slUser.IsVisible = false;
                        btnSignInSignOut.Text = "Sign in"; 
                    });
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Authentication failed. See exception message for details: ", ex.Message, "Dismiss");
            }

但是一段时间后, token 会以某种方式过期并且不会刷新。因此,它总是将用户重定向到 MS 登录页面。

我的要求是,它应该自动获取登录用户的详细信息。

可以引用这个code .

我还检查了其他选项,例如直接调用 api 来获取刷新 token ,但没有发现任何有用的信息。

如果有人对此有任何想法,请告诉我。

提前致谢。

最佳答案

目前,MSAL 已缓存您的授权,如果授权仍然有效,可以让您以静默方式登录。因此,作为用户,您无需每次使用该应用程序时都登录。

您可以使用 SecureStorage.SetAsync 来存储访问 token 。

登录:

public async Task<bool> SignInAsync()
{
 try
 {
     var accounts = await _pca.GetAccountsAsync();
    var firstAccount = accounts.FirstOrDefault();
    var authResult = await _pca.AcquireTokenSilent(Scopes, firstAccount).ExecuteAsync();

    // Store the access token securely for later use.
    await SecureStorage.SetAsync("AccessToken", authResult?.AccessToken);

    return true;
 }
 catch (MsalUiRequiredException)
 {
    try
    {
        // This means we need to login again through the MSAL window.
        var authResult = await _pca.AcquireTokenInteractive(Scopes)
                                    .WithParentActivityOrWindow(ParentWindow)
                                    .ExecuteAsync();

        // Store the access token securely for later use.
        await SecureStorage.SetAsync("AccessToken", authResult?.AccessToken);

        return true;
    }
    catch (Exception ex2)
    {
        Debug.WriteLine(ex2.ToString());
        return false;
    }
 }
 catch (Exception ex)
 {
    Debug.WriteLine(ex.ToString());
    return false;
 }
 }

关于xamarin.forms - AcquireToken 一段时间后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69163418/

相关文章:

android - Xamarin 表单 : Problem with TwoWay Binding and StringFormat

c# - 如何在 Xamarin 表单后面的代码中获取 BLE 设备的 mac 地址?

c# - Xamarin.Forms - 用于异步操作的 BeginInvokeOnMainThread

azure-active-directory - MSAL - userIdentifier 与 idToken.oid

python - 如何在 python 中使用 MSAL 获取访问 token ?

reactjs - React 中的 msal.js - Azure 身份验证

ios - 如何使 MasterDetailPage 图标 VoiceOver 易于访问?

c# - Azure AD 401 错误 - 从 Angular 客户端进行身份验证

azure - 如何在 Azure Vault 中存储 RSA key

azure - 在 Azure 中授予管理员同意