Rafa Ayadi
Rafa Ayadi

Reputation: 347

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

Upvotes: 0

Views: 2359

Answers (2)

Rafa Ayadi
Rafa Ayadi

Reputation: 347

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

Upvotes: 2

user2250152
user2250152

Reputation: 20660

If you are using MSAL.NET you can cache a token. Public client applications (desktop/mobile apps) should try to get a token from the cache before acquiring a token by another method.

Acquisition methods on confidential client applications manage the cache themselves.

Resource:

Token cache serialization in MSAL.NET

Upvotes: 0

Related Questions