Skip to content

ServiceClient excessively acquires tokens when specifying AccessTokenProviderFunctionAsync and ExternalTokenManagement typeΒ #377

Closed

Description

@jimmy3912msncom

We noticed in our logs after switching over to use the ServiceClient that for some reason it seems to excessively call to acquire an access token. It seems to call the AccessTokenProviderFunctionAsync once when instantiating the serviceClient, to acquire a token, then when you try to execute a request it seems to acquire access tokens again but this times 6 times for each request.

This means if we use the client to make:

  1. 1 API call it will try to make 7 token request calls
  2. 2 API calls it will try to make 13 token request calls
  3. ...

Client details: Microsoft.PowerPlatform.Dataverse.Client Version=[1.0.39]
Target framework: .NET 6.0

We log each of our token requests and although it uses a cache it does add confusion to our service. Below is a sample of code that can be put together to reproduce this.

Also this is a gif of what I see:
dvserviceclientexcesstokens

...
        private int _authTokenAcquiryCount = 0;
        public async Task<string> GetTokenForInstanceAsync(Uri uri)
        {
            _authTokenAcquiryCount++;
            Console.WriteLine("coming in to acquire auth again " + uri);
            return "your token logic";
        }

        protected async Task AnalyzeAsync(bool withRecordingIngestion)
        {
            var targetUri = new Uri("orgUrl");
            var serviceClient = new PowerPlatform.Dataverse.Client.ServiceClient(
                new PowerPlatform.Dataverse.Client.Model.ConnectionOptions
                {
                    AccessTokenProviderFunctionAsync = _ => GetTokenForInstanceAsync(targetUri),
                    AuthenticationType = PowerPlatform.Dataverse.Client.AuthenticationType.ExternalTokenManagement,
                    ServiceUri = targetUri,
                    ClientId = "your client id",
                },
                false,
                new PowerPlatform.Dataverse.Client.Model.ConfigurationOptions()
                {
                    UseWebApi = true
                });

            await serviceClient.ExecuteAsync(new RetrieveMultipleRequest() { Query = new QueryExpression("usersettings") });

            await serviceClient.ExecuteAsync(new RetrieveMultipleRequest() { Query = new QueryExpression("usersettings") });

            await serviceClient.ExecuteAsync(new RetrieveMultipleRequest() { Query = new QueryExpression("usersettings") });
        }
...

Activity

  1. rajyraman commented on Jun 2, 2023

    @rajyraman

    Might be related to #161

  2. jimmy3912msncom commented on Jun 2, 2023

    @jimmy3912msncom
    Author

    Natraj Yegnaraman (@rajyraman) Thanks. That issue looks right. In my case we do handle caching but it stuck out as we logged every token access request even on caching.

    The thing I don't understand is where MattB (@MattB-msft) mentioned: "Yes, this is by design,
    Each time the client needs to use the token for something, or its accessed in a way that could contact Dataverse, it requests the current access token of the token provider.
    During initialization, several calls are made to support authentication, version detection and endpoints, Client identification, and accessing user identification. Collectively these calls setup any version specific handling of subsequent calls, and populate properties for the client."

    If you see in my example, on serviceclient instantiation it calls token acquisition once. On all subsequent calls, even the same kind of request it seems to make 6 additional calls as mentioned in the original issue. What instantiation is it doing that would require it to fire on every request though?

    If this is truly needed, I would suggest adding documentation to make it clear that this is the expected behavior as none of the documentation related to this called this out to me: connectionoptions.accesstokenproviderfunctionasync. It looks like in the other issue the issuer opener also called out the same thing and this issue is fairly old.

  3. MattB-msft commented on Jun 3, 2023

    @MattB-msft
    Member

    The service client acquires a new access token on each use of the internal IOrganziation service. (acquiring it for information for example). In the onboard implementation, the service client handles the token access by determining the lifecycle of the token and returning it w/out asking MSAL for it.
    It does this because it knows the use case / scenario in play ( User Auth / or Client Cert | secret auth )

    In the case of External authentication, the service client doesn't understand the scenario, thus token caching and returning of tokens is left entirely up to the external authentication handler. The reason that we don't make assumptions About the external authentication handler is that there exists scenarios where tokens need to be evaluated on a request by request basis. In such situations simply evaluating the token life cycle and returning the cached copy without sending the request to the external authentication handler, would create a situation where the client breaks the behavior required by the external authentication provider. Should 'you' ( the external auth provider ) want to do it the same way that the Service Client does it, your welcome to copy the code we use to your provider.

  4. jimmy3912msncom commented on Jun 3, 2023

    @jimmy3912msncom
    Author

    Thank you for the explanation. I still think it would be good to document this for the client when using it so that this is not a surprise for users

  5. MattB-msft commented on Jun 6, 2023

    @MattB-msft
    Member

    Thats fair, we can discuss with docs team.
    Also we are going to push an update to reduce the number of times we ask for the token.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions