Using OAuth2, we receive the error in the topic after processing 40 or so email messages. Have you seen this error and have any idea of how to avoid it?
I’m working with a Windows service that runs unattended with username and password access, but it seems like the service runs too quickly for Azure to handle and we hit some sort of flood control. While I can making things work with a hardcoded 5 minute wait when the exception is encountered, this reduces the performance of the service to the point of being unusable.
Here’s my code for retrieving a token:
internal static class OAuthTokenProvider
{
public static OAuthNetworkCredential GetAzureToken(ref IPublicClientApplication app, string clientId, string tenantId, string redirectUri, string user, string pass, string[] scopes)
{
AuthenticationResult result = null;
if (app == null)
{
app = PublicClientApplicationBuilder
.Create(clientId)
.WithRedirectUri(redirectUri)
.WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
.Build();
}
var accounts = app.GetAccountsAsync().Result;
try
{
if (accounts.Any())
{
result = app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.WithForceRefresh(true)
.ExecuteAsync().Result;
}
else
{
result = app.AcquireTokenByUsernamePassword(scopes, user, new NetworkCredential("", pass).SecurePassword).ExecuteAsync().Result;
}
}
catch (Exception ex)
{
if (ex.InnerException != null && ex.InnerException.Message.Contains("AADSTS50196"))
{
Thread.Sleep(300000); // I want to avoid this
result = app.AcquireTokenByUsernamePassword(scopes, user, new NetworkCredential("", pass).SecurePassword).ExecuteAsync().Result;
}
else
{
throw;
}
}
return new OAuthNetworkCredential(result.AccessToken);
}
}
Thanks!