I am seeing a strange behaviour and unable to understand how do i resolve. I see that AcquireTokenInteractive is activated/called on each request of graphClient.Me.
First on await graphClient.Me.GetAsync(); (Which is expected)
and secondly on await graphClient.Me.Calendars.GetAsync(); (which is unexpected behaviour)
Below is my complete code sample.
I am using Microsoft Graph .NET SDK v5
public class TokenProvider : IAccessTokenProvider
{
public AllowedHostsValidator AllowedHostsValidator => throw new NotImplementedException();
public IPublicClientApplication publicClientApp;
public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object> additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
{
var scopes = new[] { "Calendars.Read", "User.Read" };
AuthenticationResult authResult;
publicClientApp = PublicClientApplicationBuilder.Create("0c-a5-42-a-92")
.WithRedirectUri("http://localhost")
.Build(); //Client-id
try
{
var accounts = await publicClientApp.GetAccountsAsync();
authResult = await publicClientApp.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
return authResult.AccessToken;
}
catch (MsalUiRequiredException ex)
{
authResult = await publicClientApp.AcquireTokenInteractive(scopes).ExecuteAsync();
return authResult.AccessToken;
}
}
public async Task SignOut()
{
var accounts = await publicClientApp.GetAccountsAsync();
foreach (var account in accounts)
{
await publicClientApp.RemoveAsync(account);
}
}
}
In a windows1.cs
TokenProvider tp;
BaseBearerTokenAuthenticationProvider authenticationProvider;
GraphServiceClient graphClient;
public async Task<bool> Button1_Click()
{
tp = new TokenProvider();
authenticationProvider = new BaseBearerTokenAuthenticationProvider(tp);
Microsoft.Graph.Models.User user = null;
graphClient = new GraphServiceClient(authenticationProvider);
user = await graphClient.Me.GetAsync(); // login screen is Called here First Time, expected.
}
public async Task<List<string>> Button2_Click()
{
var calendars = await graphClient.Me.Calendars.GetAsync(); // login screen is called here second time, why ?
}