protected override async Task SendAsync()

in src/ApiForFhirMigrationTool.Function/Security/BearerTokenHandler.cs [60:88]


        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Only add header for requests that don't already have one.
            if (request.Headers.Authorization is not null)
            {
                return await base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri is not null)
            {
                if (request.RequestUri.Scheme != Uri.UriSchemeHttps && request.RequestUri.Host != "localhost")
                {
                    throw new InvalidOperationException("Bearer token authentication is not permitted for non TLS protected (https) endpoints.");
                }

                var scopes = _scopes;
                if (scopes is null or { Length: 0 })
                {
                    scopes = GetDefaultScopes(request.RequestUri);
                }

                AccessToken cachedToken = await _accessTokenCache.GetTokenAsync(scopes, cancellationToken).ConfigureAwait(false);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", cachedToken.Token);

                // Send the request.
            }

            return await base.SendAsync(request, cancellationToken);
        }