Search code examples
sdkmicrosoft-graph-apimicrosoft-graph-sdks

Why is my GraphServiceClient reauthenticating at every API call?


I am using Microsoft Graph API to call some endpoints. I am using the SDK for C#. When opening a fiddler trace, I found out that my _graphClientService is issuing an authentication to get a new token at every call. Why would that happen and how to prevent it? enter image description here

It is also causing this error in some calls.

AADSTS50196: The server terminated an operation because it encountered a client request loop

Solution

  • It looks like this piece of code works. It generates a GraphServiceClient that reuses the same token at every call, instead of generating a new one.

     public GraphServiceClient GenerateGraphUserClient()
        {
            string userToken = GetUserAccessToken();
            GraphServiceClient client= new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(async (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", userToken);
            }));
            return client;
        }
    
    public string GetUserAccessToken()
        {
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create(_clientId)
            .WithTenantId(_domain)
            .Build();
            var securePassword = new SecureString();
            foreach (char c in _password)
                securePassword.AppendChar(c);
            var result = publicClientApplication.AcquireTokenByUsernamePassword(scopes, _userName, securePassword).ExecuteAsync().Result;
            return result.AccessToken;
        }
    

    enter image description here