Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ConfidentialClientApplication.AcquireTokenForClient().ExecuteAsync() thread safe?

For service to service auth using a bearer token for the app (client id and secret no user context) in .net core using MSAL.NET v4 (nuget Microsoft.Identity.Client v4.3.0) is ConfidentialClientApplication.AcquireTokenForClient().ExecuteAsync() safe to use in a singleton registered service implemented like this?

public class AADConfidentialClient : IServiceApiAuthorizer
    {
        private readonly IConfidentialClientApplication _confidentialClient;
        public AADConfidentialClient(IOptions<ConfidentialClientApplicationOptions> options)
        {
            _confidentialClient = ConfidentialClientApplicationBuilder
                     .CreateWithApplicationOptions(options.Value)
                     .Build();
        }

        public async Task<string> GetTokenAsync(IReadOnlyCollection<string> scopes)
        {
            var result = await _confidentialClient.AcquireTokenForClient(scopes).ExecuteAsync();

            return result.AccessToken;
        }
    }

Registered with the .net core built-in DI as

services.AddSingleton<IServiceApiAuthorizer, AADConfidentialClient>();

I've seen this answer for ADAL.NET https://stackoverflow.com/a/53163274/184220 which mentions working towards thread safety for MSAL v2+ but haven't found anything confirming if this has been done.

like image 891
Aquila Sands Avatar asked Aug 23 '19 16:08

Aquila Sands


1 Answers

For the client credentials flow this uses it is safe to be a singleton. I eventually found this question in the GitHub issues https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1342 which was about the on behalf of flow which had this answer to one of the questions:

You should have 1 Confidential Client Application for each token cache. And we recommend that you have 1 token cache per session, so there should be 1 CCA per session.

As the implementation in this question essentially has 1 token cache I thought it would be safe but asked for confirmation anyway and this https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1342#issuecomment-525286547 was the answer:

yes, for Client Credentials flow a singleton should work fine. You are requesting tokens for an application, not for a user. There will only be 1 access token in the in-memory cache (for the app), irrespective of how many users and sessions there are

like image 99
Aquila Sands Avatar answered Oct 02 '22 11:10

Aquila Sands