Reputation: 347
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?
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
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;
}
Upvotes: 2
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