microsoft-authentication-library-for-dotnet: [Investigate] B2C Xamarin Sample getAccounts does not return an account after first sign-in

My Code

        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;
        }

Expected behavior

After first login, I think _pca.GetAccountsAsync() should return accounts list and be able to refresh token

Actual behavior

always _pca.GetAccountsAsync() returns empty array so, can’t refresh token So it ask to login every time app launches.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 16 (3 by maintainers)

Most upvoted comments

@jennyf19 , I am using simulator- google pixel-2 Pie 9.0

@jennyf19 , almost didn’t changed, but the authentication code is the code provided