【问题标题】:IPublicClientApplication.GetAccountsAsync() returns only empty arrayIPublicClientApplication.GetAccountsAsync() 仅返回空数组
【发布时间】:2020-10-15 17:34:41
【问题描述】:

IPublicClientApplication.GetAccountsAsync() 在 xamarin 表单应用程序中仅返回空数组。 所以每次应用启动时它都会要求登录。

-- 预期行为 首次登录后,我认为 _pca.GetAccountsAsync() 应该返回帐户列表并能够刷新令牌

-- 实际行为 总是 _pca.GetAccountsAsync() 返回空数组,因此无法刷新令牌 所以每次应用启动时它都会要求登录。

    public async Task<UserContext> SingInWithoutInteractively()
    {
        UserContext newContext;
        try
        {
            // acquire token silent
            newContext = await AcquireToken();

        } catch
        {
            newContext = null;
        }

        return newContext;
    }

    public async Task<UserContext> SignInAsync()
    {
        UserContext newContext;
        try
        {
            // acquire token silent
            newContext = await AcquireToken();
        }
        catch (MsalUiRequiredException)
        {
            // acquire token interactive
            newContext = await SignInInteractively();
        }
        return newContext;
    }

    private async Task<UserContext> AcquireToken()
    {
        IEnumerable<IAccount> accounts = await _pca.GetAccountsAsync();
        AuthenticationResult authResult = await _pca.AcquireTokenSilent(B2CConstants.Scopes, GetAccountByPolicy(accounts, B2CConstants.PolicySignUpSignIn))
           .WithB2CAuthority(B2CConstants.AuthoritySignInSignUp)
           .ExecuteAsync();
        
        var newContext = UpdateUserInfo(authResult);
        return newContext;
    }
    private async Task<UserContext> SignInInteractively()
    {
        IEnumerable<IAccount> accounts = await _pca.GetAccountsAsync();

        AuthenticationResult authResult = await _pca.AcquireTokenInteractive(B2CConstants.Scopes)
            .WithPrompt(Prompt.SelectAccount)
            .WithAccount(GetAccountByPolicy(accounts, B2CConstants.PolicySignUpSignIn))
            .ExecuteAsync();
        
        var newContext = UpdateUserInfo(authResult);            
        return newContext;
    }
    private IAccount GetAccountByPolicy(IEnumerable<IAccount> accounts, string policy)
    {
        foreach (var account in accounts)
        {
            string userIdentifier = account.HomeAccountId.ObjectId.Split('.')[0];
            if (userIdentifier.EndsWith(policy.ToLower())) return account;
        }

        return null;
    }

【问题讨论】:

  • 您好,这是Github 中的一个讨论,您可以检查一下它是否解决了您的问题。

标签: .net xamarin.forms azure-ad-b2c msal


【解决方案1】:

尝试使用以下代码:

[MsalUiRequiredExceptionFilter(Scopes = new [] {Constants.ScopeUserRead})]

请看:here

【讨论】:

    【解决方案2】:

    添加openid作用域后,这个问题就解决了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 2017-02-27
      • 2020-04-01
      • 2019-04-17
      相关资源
      最近更新 更多