Example #1
0
        public async Task <TReturnType> GetAsync <TReturnType>(string controllerName, string actionName = null, IEnumerable <KeyValuePair <string, string> > parameters = null, CancellationToken cancellationToken = default)
        {
            Uri uri         = CreateUri(controllerName, actionName, parameters);
            var accessToken = await accessTokenProvider.GetAccessTokenAsync(cancellationToken);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            return(await client.GetFromJsonAsync <TReturnType>(uri, cancellationToken));
        }
Example #2
0
        public async Task <string> GetTokenAsync(string registryServer, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNullOrEmpty(registryServer, nameof(registryServer));

            string aadToken;

            try
            {
                aadToken = await _aadTokenProvider.GetAccessTokenAsync(ContainerRegistryConstants.ArmResourceManagerIdForAzureCloud, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to get AAD access token from managed identity.");
                throw new ContainerRegistryTokenException("Failed to get AAD access token from managed identity.", ex);
            }

            try
            {
                return(await Policy
                       .Handle <HttpRequestException>()
                       .RetryAsync(3, onRetry: (exception, retryCount) =>
                {
                    _logger.LogWarning(exception, "Get ACR token failed. Retry {RetryCount}.", retryCount);
                })
                       .ExecuteAsync(() => GetAcrAccessTokenWithAadToken(registryServer, aadToken, cancellationToken)));
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError(ex, "Failed to get ACR access token with AAD access token.");
                throw new ContainerRegistryTokenException("Failed to get ACR access token with AAD access token.", ex);
            }
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var token = await accessTokenProvider.GetAccessTokenAsync();

            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
                "Bearer", token);
            return(await base.SendAsync(request, cancellationToken));
        }
        /// <summary>
        /// Requests a new access token from server and saves it to file.
        /// </summary>
        private static async Task RenewToken()
        {
            Log("Access token has expired. Requesting new access token.");
            AccessToken token = await _accessTokenProvider.GetAccessTokenAsync();

            _tripPlannerProvider.SetToken(token);

            Log("Save access token.", "Out");
            string serialized = Serialize(token);
            await FileIO.WriteTextAsync(_accessTokenFile, serialized);
        }
Example #5
0
        /// <summary>
        /// Performs the necessary authentication and injects the required header.
        /// </summary>
        /// <param name="request">The request being made to the Microsoft Graph API.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            AuthenticationResult token = await tokenProvider.GetAccessTokenAsync(
                $"{ApplicationConfiguration.ActiveDirectoryEndPoint}{customerId}",
                authorizationCode,
                redirectUri,
                new ClientCredential(
                    ApplicationConfiguration.ActiveDirectoryClientID,
                    ApplicationConfiguration.ActiveDirectoryClientSecret),
                "https://graph.microsoft.com").ConfigureAwait(false);

            request.Headers.Add(AuthHeaderName, $"{TokenType} {token.AccessToken}");
        }
Example #6
0
        /// <summary>
        /// Performs the necessary authentication and injects the required header.
        /// </summary>
        /// <param name="request">The request being made to the Microsoft Graph API.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            SecureClientSecret clientSecret = new SecureClientSecret(
                await ApplicationDomain.Instance.KeyVaultService.GetAsync(WebPortalADClientSecretKey).ConfigureAwait(false));

            AuthenticationResult token = await tokenProvider.GetAccessTokenAsync(
                $"{ApplicationConfiguration.ActiveDirectoryEndPoint}{customerId}",
                authorizationCode,
                redirectUri,
                new ClientCredential(
                    ApplicationConfiguration.ActiveDirectoryClientID,
                    clientSecret),
                "https://graph.microsoft.com").ConfigureAwait(false);

            request.Headers.Add(AuthHeaderName, $"{TokenType} {token.AccessToken}");
        }
Example #7
0
        public async Task <string> SearchAsync(
            BaseFhirApiOptions fhirApiOptions,
            CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException();
            }

            Uri searchUri;

            try
            {
                searchUri = CreateSearchUri(fhirApiOptions);
            }
            catch (Exception ex)
            {
                _logger.LogError("Create search Uri failed, Reason: '{reason}'", ex);
                throw new FhirSearchException("Create search Uri failed", ex);
            }

            string accessToken = null;

            if (fhirApiOptions.IsAccessTokenRequired)
            {
                try
                {
                    if (_dataSource.Authentication == AuthenticationType.ManagedIdentity)
                    {
                        // Currently we support accessing FHIR server endpoints with Managed Identity.
                        // Obtaining access token against a resource uri only works with Azure API for FHIR now.
                        // To do: add configuration for OSS FHIR server endpoints.

                        // The thread-safe AzureServiceTokenProvider class caches the token in memory and retrieves it from Azure AD just before expiration.
                        // https://docs.microsoft.com/en-us/dotnet/api/overview/azure/service-to-service-authentication#using-the-library
                        accessToken = await _accessTokenProvider.GetAccessTokenAsync(_dataSource.FhirServerUrl, cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("Get fhir server access token failed, Reason: '{reason}'", ex);
                    throw new FhirSearchException("Get fhir server access token failed", ex);
                }
            }

            return(await GetResponseFromHttpRequestAsync(searchUri, accessToken, cancellationToken));
        }
Example #8
0
        private async Task <String> MakeHttpRequest <T>(String method, String entity, ApiMessage <T> apimessage = null, string extraurl = "") where T : BaseModel
        {
            string json   = Serialize(apimessage);
            var    client = new System.Net.Http.HttpClient();

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            client.DefaultRequestHeaders.Add("User-Agent", "AnimeRaiku C# SDK");

            var accessToken = await acccessTokenProvider.GetAccessTokenAsync();

            if (accessToken != null)
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken.AccessToken);
            }

            var domain = configuration.BaseUrl;

            if (!domain.EndsWith("/"))
            {
                domain += '/';
            }

            Task <HttpResponseMessage> task = null;

            if (method == "GET")
            {
                task = client.GetAsync(domain + entity + extraurl);
            }

            if (method == "POST")
            {
                task = client.PostAsync(domain + entity + extraurl, new StringContent(json, Encoding.UTF8, "application/json"));
            }

            HttpResponseMessage msg = await task;

            HttpContent stream = (HttpContent)msg.Content;

            String data = await stream.ReadAsStringAsync();

            return(data);
        }
Example #9
0
        public virtual async Task <string> GetAccessTokenAsync()
        {
            var options = await _weChatOfficialOptionsResolver.ResolveAsync();

            return(await _accessTokenProvider.GetAccessTokenAsync(options.AppId, options.AppSecret));
        }
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var token = _tokenProvider.GetAccessTokenAsync().Result;

            request.AddOrUpdateParameter("Authorization", $"Bearer {token}", ParameterType.HttpHeader);
        }
        public static async Task Initialize()
        {
            _logger = new OutputLogger(typeof(TripPlannerProviderPassthrough));

            Log("Initializing TripPlannerProvider.");
            _accessTokenProvider = new AccessTokenProvider()
            {
                Logger = new OutputLogger(nameof(AccessTokenProvider))
            };
            _accessTokenFolder = ApplicationData.Current.LocalFolder;

            if (!File.Exists(_accessTokenFolder.Path + "\\CurrentAccessToken.txt") || await IsFileEmpty())
            {
                _accessTokenFile = await _accessTokenFolder.CreateFileAsync("CurrentAccessToken.txt", CreationCollisionOption.ReplaceExisting);

                Log("Created new access token file.", "Out");
            }
            else
            {
                _accessTokenFile = await _accessTokenFolder.GetFileAsync("CurrentAccessToken.txt");

                Log("Load access token from file.", "In");
            }

            AccessToken token;

            Func <Task <AccessToken> > createNewToken = async() =>
            {
                AccessToken newAccessToken = await _accessTokenProvider.GetAccessTokenAsync();

                string serialized = Serialize(newAccessToken);
                await FileIO.WriteTextAsync(_accessTokenFile, serialized);

                return(newAccessToken);
            };

            if (await IsFileEmpty()) // File should be empty if the file was just created.
            {
                Log("Could not find access token on file.");
                token = await createNewToken();
            }
            else
            {
                var data = await FileIO.ReadLinesAsync(_accessTokenFile);

                string[]    serializedRetrieved  = data.ToArray();
                AccessToken retrievedAccessToken = Deserialize(serializedRetrieved);
                if (retrievedAccessToken.ExpiresDateTime < DateTime.Now)
                {
                    Log("Access token has expired. Requesting new access token.");
                    token = await createNewToken();
                }
                else
                {
                    token = retrievedAccessToken;
                }
            }

            _tripPlannerProvider = new TripPlannerProvider(token)
            {
                Logger = new OutputLogger(nameof(TripPlannerProvider))
            };
            //_tripPlannerProvider = new TripPlannerProviderMock();

            Log($"Access token is valid to {token.ExpiresDateTime}.", "Info");
            Log("Initializing complete.");
        }