Search code examples
c#.netmicrosoft-graph-apiazure-ad-msal

MSAL.net or Graph SDK for backend applications


I'm creating a backend service running in background without direct user interaction. It is written in .NET 4.8, and runs as a windows service. The application will interact with a few endpoints (/users and /groups) of the Graph API, which means creating my own HttpClient is easy to do, as the number of endpoints invoked is limited. The application should acquire an access token from Azure, based on a client secret. I have been using the ConfidentialClientApplicationBuilder and used the AcquireTokenForClient() method of Microsoft.Identity.Client namespace, to acquire a valid access token from Azure that can be used for any further calls to Graph, but the issue is, I'm not getting a refresh_token in the response of AcquireTokenForClient(), and there is no built-in refresh mechanism as far as I see?

        private async Task<string> AcquireAccessTokenAsync()
        {
            try
            {
                var app = ConfidentialClientApplicationBuilder.Create("MyClientId")
                    .WithClientSecret("MyClientSecret")
                    .WithAuthority(new Uri("MyAuthority"))
                    .Build();
                var acquireResult = await app.AcquireTokenForClient("RequiredScopes").ExecuteAsync();
                return acquireResult.AccessToken;
            }
            catch (MsalClientException ex)
            {
                Console.WriteLine(ex);
                throw new ApplicationException("Failed to acquire access token from Azure.");
            }
        }

It feels like using the Graph SDK (Graph Client) is a little overkill for the task, which is why I attempted to use the MSAL .NET library instead. But what is the right library to use when building backend services who needs an integration into Microsoft Graph? How does it support token refresh mechanism?


Solution

  • After investigating the Client SDK furhter, and executed some test, it seems like the SDK will handle internally via a Cache, whether there is an active valid token in cache, otherwise issuing a new token request. There is no refresh token for client Credential flows used for application services without user interaction.