Which Version of MSAL are you using ?
Microsoft Identity 4.7.1
Platform
Xamarin.Forms on iOS and Android
What authentication flow has the issue?
Other? - AcquireTokenSilent
Is this a new or existing app?
This is a new app.
Repro
Login to AD B2C with email credentials. Create a loop that calls AcquireTokensSilent repeatedly. Notice that a new access token is returned every time, even though it is not close to expiring.
public async Task<UserContext> AcquireAccessToken()
{
IEnumerable<IAccount> accounts = await PCA.GetAccountsAsync();
AuthenticationResult authResult = await PCA.AcquireTokenSilent(_configuration.Scopes, GetAccountByPolicy(accounts, _configuration.PolicySignUpIn))
.WithB2CAuthority(_configuration.AuthoritySignInUp)
.ExecuteAsync();
var newContext = UpdateUserInfo(authResult);
AccessToken = newContext.AccessToken;
Debug.WriteLine($"Access token is {newContext.AccessToken}");
return newContext;
}
Expected behavior
I expected that the access token would be pulled from cache and not refreshed.
Actual behavior
Access token is refreshed every time, even when it doesn't need to be.
GetAccountByPolicy(accounts, _configuration.PolicySignUpIn) return anything?public string[] Scopes => new string[] { $"https://{Tenant}/mobileapi/user_impersonation", "offline_access" };GetAccountByPolicy seems like it returns the account correctly. The fields are populate except for username, which says "Missing from Token response".Ok, for point 2 this looks ok, it is expected that some Identity Providers do not return a username by default.
For point 1, I think the issue is similar to https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1547
Can you try to remove offline_access and see if works ? MSAL requests that scope anyway, but worth a try.
Yeah, I think this is the problem. MSAL requests offline_access but ESTS when it responds does not add offline_access to the response (mind you, it does give you a refresh token). This causes a problem in the token cache.
@jmprieur @henrik-me, @shoatman - I think we can make a small fix for this in MSAL, i.e. if the developer asks for offline_access, do not use this scope to look in the cache. Alternatively, we can ban people from explicitly asking for offline_access, but that is more intrusive.
I can confirm, removing offline_access caused it to use the cached token. I wasn't sure if I needed that, so I'll take it off. Thanks for the help!
As per internal discussion seems like we have to improve the cache lookup filtering out OIDC scopes? I don't think we should ask people to do anything we should be able to filter correctly and do appropriate cache lookup.
Yes, I'll propose a PR shortly.