为什么 MAUI Windows 上的 MSAL 在应用程序重新启动之间不缓存帐户?

问题描述 投票:0回答:1

在 MAUI .Net 8.0 应用程序中,我实现了 MSAL。在 Windows 上运行时,行

var accounts = await _pca!.GetAccountsAsync();
在应用程序重新启动后始终返回 0 个帐户,即使我在关闭并重新启动应用程序之前成功进行了身份验证。

我的期望是,该行代码将返回 1 个帐户,然后我可以使用该帐户以静默方式检索身份验证令牌并使用该身份验证令牌访问 Microsoft 服务,并且在 Android 上运行时相同的代码确实可以做到这一点。

Windows 上发生的情况是,MSAL 登录窗口始终在应用程序重新启动后启动,迫使我选择要用于进行身份验证的帐户。成功验证一次后,我不需要在此帮助程序窗口中输入密码和其他验证详细信息,我只需选择帐户并假设它与我之前使用的帐户相同,然后重复验证直至询问我密码等等都不需要。

补充一点,我不知道这是否与问题有关,要求我选择帐户的 MSAL 登录窗口 99% 的时间都是空白的。当我将鼠标悬停在通常显示帐户的区域上时,光标会变成手形,指示那里有一个链接,我只需单击它,它就会以与我可以看到帐户名称相同的方式选择该帐户- 请参阅下面的屏幕截图:

Blank MSAL login window

以下是来自

IPublicClientApplication
对象的日志 - 这是来自应用程序的第二次运行,在应用程序的第一次运行期间已成功进行身份验证:

Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z] [Internal cache] Total number of cache partitions found while getting refresh tokens: 0
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - 5882229a-d1f6-4ebd-a4c4-fae34be2ebb8] [Region discovery] Not using a regional authority. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z] Found 0 cache accounts and 0 broker accounts
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z] Returning 0 accounts
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] MSAL MSAL.NetCore with assembly version '4.59.0.0'. CorrelationId(d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b)
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] === InteractiveParameters Data ===
LoginHint provided: False
User provided: False
UseEmbeddedWebView: NotSpecified
ExtraScopesToConsent: 
Prompt: not_specified
HasCustomWebUi: False

Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] 
=== Request Data ===
Authority Provided? - True
Scopes - https://outlook.office.com/POP.AccessAsUser.All
Extra Query Params Keys (space separated) - 
ApiId - AcquireTokenInteractive
IsConfidentialClient - False
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured: 

Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] === Token Acquisition (InteractiveRequest) started:
     Scopes: https://outlook.office.com/POP.AccessAsUser.All
    Authority Host: login.microsoftonline.com
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] [Instance Discovery] Instance discovery is enabled and will be performed
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] [Region discovery] Not using a regional authority. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:19Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Fetching instance discovery from the network from host login.microsoftonline.com. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:20Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Authority validation enabled? True. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:20Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Authority validation - is known env? True. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:20Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Using WebView1 embedded browser because the authority is Aad. WebView2 does not provide SSO.
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] [Legacy WebView] Redirect URI was reached. Stopping WebView navigation...
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] An authorization code was retrieved from the /authorize endpoint. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Exchanging the auth code for tokens. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] === InteractiveParameters Data ===
LoginHint provided: False
User provided: False
UseEmbeddedWebView: NotSpecified
ExtraScopesToConsent: 
Prompt: not_specified
HasCustomWebUi: False

Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Checking client info returned from the server..
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Saving token response to cache..
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] [Region discovery] Not using a regional authority. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] [SaveTokenResponseAsync] Saving AT in cache and removing overlapping ATs...
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Looking for scopes for the authority in the cache which intersect with https://outlook.office.com/POP.AccessAsUser.All
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z] [Internal cache] Total number of cache partitions found while getting access tokens: 0
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Intersecting scope entries count - 0
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Matching entries after filtering by user - 0
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] [SaveTokenResponseAsync] Saving Id Token and Account in cache ...
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] [SaveTokenResponseAsync] Saving RT in cache...
'MSALTestApp.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.1\System.Collections.Immutable.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] 
    === Token Acquisition finished successfully:
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b]  AT expiration time: 29/02/2024 13:48:08 +00:00, scopes: https://outlook.office.com/POP.AccessAsUser.All. source: IdentityProvider
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] Fetched access token from host login.microsoftonline.com. 
Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] 
[LogMetricsFromAuthResult] Cache Refresh Reason: NotApplicable
[LogMetricsFromAuthResult] DurationInCacheInMs: 0
[LogMetricsFromAuthResult] DurationTotalInMs: 5814
[LogMetricsFromAuthResult] DurationInHttpInMs: 720

Information: False MSAL 4.59.0.0 MSAL.NetCore .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-02-29 12:24:25Z - d2b38fd1-46b0-4ab2-8ba8-e6dd6864241b] TokenEndpoint: ****

我已经设置了一个包含代码的存储库来复制此问题:https://github.com/benempson/msal-test

IPublicClientApplication
对象在 Platforms 文件夹内的各个
PlatformSetup.cs
部分类中进行配置,
Setup()
方法,依次从
MauiProgram.cs
调用。实际的身份验证调用是在
Home.razor
文件中进行的。

我在这里做错了什么?所有 MSAL 代码均取自 Microsoft 示例。

编辑:只需添加设置代码,使其在此处可见: PlatformSetup.cs(_serviceCollection 是 DI 容器):

string? clientId = SecureStorage.GetAsync("ClientId").Result;
PublicClientApplicationBuilder pcab = PublicClientApplicationBuilder
    .Create(clientId)
    .WithAuthority(AzureCloudInstance.AzurePublic, "common")
    .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
    .WithLogging((level, message, pii) =>
    {
        _logger.LogInformation(message);
    }, Microsoft.Identity.Client.LogLevel.Info, enablePiiLogging: false, enableDefaultPlatformLogging: true);

_serviceCollection.AddSingleton<IPublicClientApplication>(pcab.Build());

Home.razor:

@page "/"
@inject Microsoft.Identity.Client.IPublicClientApplication _pca
@using System.Text.Json

<h1>Hello, world!</h1>

@_log


@code {
    private MarkupString _log;

    private string[] _scopes = new[] {
        "https://outlook.office.com/POP.AccessAsUser.All",
    };

    protected override async Task OnInitializedAsync()
    {
        StringBuilder log = new StringBuilder();
        AuthenticationResult authResult;
        var accounts = await _pca!.GetAccountsAsync();
        log.AppendLine($"Found {accounts.Count()} cached accounts");
        bool needsInteractiveLogin = accounts.Count() < 1;
        if (!needsInteractiveLogin)
        {
            try
            {
                authResult = await _pca!
                    .AcquireTokenSilent(_scopes, accounts.FirstOrDefault())
                    .ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                needsInteractiveLogin = true;
            }
            catch (Exception ex)
            {
                log.AppendLine($"MSAL silent error: {ex.Message}");
            }
        }

        if (needsInteractiveLogin)
        {
            log.AppendLine("Doing interactive login");
            try
            {
                authResult = await _pca!
                    .AcquireTokenInteractive(_scopes)
                    .ExecuteAsync();

                log.AppendLine($"authResult = {(authResult == null ? "null" : $"Authenticated: {authResult.Account.HomeAccountId}")}");
            }
            catch (Exception ex)
            {
                log.AppendLine($"MSAL interactive error: {ex.Message}");
            }
        }
        else
            log.AppendLine("No interactive login required");

        _log = new MarkupString(log.ToString().ReplaceLineEndings($"<br />{Environment.NewLine}"));
        await base.OnInitializedAsync();
    }
}
maui azure-ad-msal
1个回答
0
投票

提出问题 3 个月后,在验证码没有更改的情况下,它随机开始按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.