MSAL: Acquire access token without throttling

sravya shivapuram 211 Reputation points
2022-03-28T14:31:31.49+00:00

Hi,

I am currently working on an azure function to delete the power automate flows for the SharePoint sites that have completed the approval workflow. As part of this, I am generating the bearer/access token using MSAL as shown below - I am calling the GetAuthToken method in a foreach loop ( Because it needs to loop through SharePoint sites)

var bToken = await GetAuthToken(_settings.Clientid, scope, _settings.TenantId);

internal static async Task<string> GetAuthToken(string clientId, string[] scopes, string tenantId)
        {
            string authority = "https://login.microsoftonline.com/" + tenantId;
            try
            {
                IPublicClientApplication clientApp = PublicClientApplicationBuilder
                                                .Create(clientId)
                                                .WithAuthority(authority)
                                                .Build();
                var securePassword = new SecureString();
                foreach (char c in Base64Decode(ServiceAccountp)) // you should fetch the password
                {
                    securePassword.AppendChar(c); // keystroke by keystroke
                }
                AuthenticationResult authResult = await clientApp.AcquireTokenByUsernamePassword(scopes,
                    Base64Decode(ServiceAccountun),
                    securePassword)
                    .ExecuteAsync();
                string accessToken = authResult.AccessToken;
                return accessToken;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        private static string Base64Decode(string base64EncodedData)
        {
            var base64EncodedBytes = Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }

This worked a few times but I saw the below exception a couple of times :

Microsoft.Identity.Client.MsalUiRequiredException: Your app has been throttled by AAD due to too many requests. To avoid this, cache your tokens see https://aka.ms/msal-net-throttling.

Is there a way to prevent the above exception and handle it in an optimized way?

Any help is greatly appreciated. Thank you in advance.

Regards
SLS

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
17,543 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Shweta Mathur 22,651 Reputation points Microsoft Employee
    2022-03-29T07:16:21.323+00:00

    Hi @sravya shivapuram ,

    Thanks for reaching out.

    I understand that you have requirement to acquire token continuously to access each Sharepoint site and Microsoft Identity is throttling your requests.

    When application acquire token without waiting, they can produce a heavy load on the infrastructure and continue to be throttled. This will prevent your application from receiving tokens and your application responds with HTTP 429 - Too Many Requests response code.

    We recommend implementing an exponential back-off retry with the first retry at least after few seconds after the response. In this approach, a client application periodically retries a failed request with increasing delays between requests.

    Retry =  
     {  
         Delay= TimeSpan.FromSeconds(2),  
         MaxDelay = TimeSpan.FromSeconds(16),  
         MaxRetries = 5,  
         Mode = RetryMode.Exponential  
      }  
    

    Example:

    1.Make request to services.
    2.If the request fails, wait 1 seconds and retry the request.
    3.If the request fails, wait 2 seconds and retry the request.
    4.If the request fails, wait 4 seconds and retry the request.
    5.If the request fails, wait 8 seconds and retry the request.
    6.If the request fails, wait 16 seconds and retry the request.

    The wait time is min (2^n), with n incremented by 1 for each request.

    This will help to avoid throttling and acquire token correctly.

    Thanks,
    Shweta


    Please remember to "Accept Answer" if answer helped you.