예제 #1
0
        /// <summary>
        /// Wraps an API request - if the request is unauthorized it will refresh the Auth token and re-issue the request
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        private async Task <IApiResponse> WrapApiRequestAsync(OAuthAuthorization authResponse, Func <OAuthAuthorization, Task <IApiResponse> > func)
        {
            try
            {
                return(await func(authResponse));
            }
            catch (DigikeyUnauthorizedException ex)
            {
                // get refresh token, retry
                _oAuth2Service.ClientSettings.RefreshToken = ex.Authorization.RefreshToken;
                var token = await _oAuth2Service.RefreshTokenAsync();

                var refreshTokenResponse = new OAuthAuthorization(nameof(DigikeyApi), _oAuth2Service.ClientSettings.ClientId, _httpContextAccessor.HttpContext.Request.Headers["Referer"].ToString())
                {
                    AccessToken           = token.AccessToken,
                    RefreshToken          = token.RefreshToken,
                    CreatedUtc            = DateTime.UtcNow,
                    ExpiresUtc            = DateTime.UtcNow.Add(TimeSpan.FromSeconds(token.ExpiresIn)),
                    AuthorizationReceived = true,
                };
                var contextKey = $"{nameof(DigikeyApi)}-{_httpContextAccessor.HttpContext.User.Identity.Name}";
                ServerContext.Set(contextKey, refreshTokenResponse);
                if (refreshTokenResponse.IsAuthorized)
                {
                    // save the credential
                    await _credentialService.SaveOAuthCredentialAsync(new Common.Models.OAuthCredential
                    {
                        Provider       = contextKey,
                        AccessToken    = refreshTokenResponse.AccessToken,
                        RefreshToken   = refreshTokenResponse.RefreshToken,
                        DateCreatedUtc = refreshTokenResponse.CreatedUtc,
                        DateExpiresUtc = refreshTokenResponse.ExpiresUtc,
                    });

                    try
                    {
                        // call the API again using the refresh token
                        return(await func(refreshTokenResponse));
                    }
                    catch (DigikeyUnauthorizedException)
                    {
                        // refresh token failed, restart access token retrieval process
                        await ForgetAuthenticationTokens();

                        var freshResponse = await AuthorizeAsync();

                        if (freshResponse.MustAuthorize)
                        {
                            return(ApiResponse.Create(true, freshResponse.AuthorizationUrl, $"User must authorize", nameof(DigikeyApi)));
                        }
                        // call the API again
                        return(await func(freshResponse));
                    }
                }
                throw new UnauthorizedAccessException("Unable to authenticate with Digikey!");
            }
        }
예제 #2
0
        private async Task CallKeywordSearch()
        {
            var settings = ApiClientSettings.CreateFromConfigFile();

            _log.DebugFormat(settings.ToString());
            Console.WriteLine(settings.ToString());
            try
            {
                if (settings.ExpirationDateTime < DateTime.Now)
                {
                    // Let's refresh the token
                    var oAuth2Service     = new OAuth2Service(settings);
                    var oAuth2AccessToken = await oAuth2Service.RefreshTokenAsync();

                    if (oAuth2AccessToken.IsError)
                    {
                        // Current Refresh token is invalid or expired
                        _log.DebugFormat("Current Refresh token is invalid or expired ");
                        Console.WriteLine("Current Refresh token is invalid or expired ");
                        return;
                    }

                    settings.UpdateAndSave(oAuth2AccessToken);

                    _log.DebugFormat("After call to refresh");
                    _log.DebugFormat(settings.ToString());

                    Console.WriteLine("After call to refresh");
                    Console.WriteLine(settings.ToString());
                }

                var client   = new ApiClientService(settings);
                var response = await client.KeywordSearch("P5555-ND");

                // In order to pretty print the json object we need to do the following
                var jsonFormatted = JToken.Parse(response).ToString(Formatting.Indented);

                Console.WriteLine($"Reponse is {jsonFormatted} ");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public void ResetExpiredAccessTokenIfNeeded()
        {
            if (_clientSettings.ExpirationDateTime < DateTime.Now)
            {
                // Let's refresh the token
                var oAuth2Service     = new OAuth2Service(_clientSettings);
                var oAuth2AccessToken = oAuth2Service.RefreshTokenAsync().Result;
                if (oAuth2AccessToken.IsError)
                {
                    // Current Refresh token is invalid or expired
                    Console.WriteLine("Current Refresh token is invalid or expired ");
                    return;
                }

                // Update the clientSettings
                _clientSettings.UpdateAndSave(oAuth2AccessToken);
                Console.WriteLine("ApiClientService::CheckifAccessTokenIsExpired() call to refresh");
                Console.WriteLine(_clientSettings.ToString());

                // Reset the Authorization header value with the new access token.
                var authenticationHeaderValue = new AuthenticationHeaderValue("Authorization", _clientSettings.AccessToken);
                HttpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
            }
        }
예제 #4
0
        public async Task <string> Get([FromQuery] string partId, [FromQuery] string quantity, [FromQuery] string currency)
        {
            // string apiToken = "41c44903-fdc0-417c-abb9-6c79bbad03f1";
            //partId =string.IsNullOrEmpty(partId)? "GRM21BR71C225KA12L" : partId;
            // string mouserUrl = "https://api.mouser.com/api/v1/search/partnumber";
            // MouserRoot restResponse = new MouserRoot();
            // HttpClient client = new HttpClient();
            // Models.ValueRow pResponse = new Models.ValueRow();
            //// client.DefaultRequestHeaders.Add("Content-Type", "application/json");
            // try
            // {
            //     pResponse.PartNumber = partId;
            //     pResponse.Quantity =Convert.ToInt32( string.IsNullOrEmpty(quantity) ? "1" : quantity);
            //     Models.Rootobject bodyParam = new Models.Rootobject() { SearchByPartRequest = new Models.Searchbypartrequest() { mouserPartNumber = partId } };
            //     string json = JsonConvert.SerializeObject(bodyParam);
            //     mouserUrl += "?apiKey=";
            //     mouserUrl += apiToken;
            //     HttpRequestMessage mouserRequest = new HttpRequestMessage()
            //     {
            //         Method = HttpMethod.Post,
            //         RequestUri = new Uri(mouserUrl),
            //         Content = new StringContent(json, Encoding.UTF8, "application/json")

            //     };

            //     HttpResponseMessage response = await client.SendAsync(mouserRequest).ConfigureAwait(false);
            //     response.EnsureSuccessStatusCode();
            //     string responseBody = await response.Content.ReadAsStringAsync();

            //     restResponse = JsonConvert.DeserializeObject<MouserRoot>(responseBody);
            //     if (restResponse.SearchResults.Parts.Count() > 0)
            //     {

            //         pResponse.Manufacturer = restResponse.SearchResults.Parts[0].Manufacturer;
            //         pResponse.Mouser = new Models.Mouser() { LeadTime = restResponse.SearchResults.Parts[0].LeadTime, AvailableQuantity = restResponse.SearchResults.Parts[0].Availability ,PriceBreakups = new List<Models.PriceBreakUp>()};
            //         if (restResponse.SearchResults.Parts[0].PriceBreaks.Count() > 0)
            //         {
            //             for (int i = 0; i < restResponse.SearchResults.Parts[0].PriceBreaks.Count(); i++)
            //             {
            //                 pResponse.Mouser.PriceBreakups.Add(new Models.PriceBreakUp() { Price = restResponse.SearchResults.Parts[0].PriceBreaks[i].Price, Quantity = restResponse.SearchResults.Parts[0].PriceBreaks[i].Quantity.ToString() });
            //             }
            //         }
            //     }
            // }
            // catch (HttpRequestException e)
            // {
            //     throw;
            // }

            // return pResponse;



            var    settings      = ApiClientSettings.CreateFromConfigFile();
            string jsonFormatted = "";

            try
            {
                if (settings.ExpirationDateTime < DateTime.Now)
                {
                    // Let's refresh the token
                    var oAuth2Service     = new OAuth2Service(settings);
                    var oAuth2AccessToken = oAuth2Service.RefreshTokenAsync().Result;
                    if (oAuth2AccessToken.IsError)
                    {
                        // Current Refresh token is invalid or expired

                        return(null);
                    }

                    settings.UpdateAndSave(oAuth2AccessToken);


                    Console.WriteLine("After call to refresh");
                    Console.WriteLine(settings.ToString());
                }

                var client   = new ApiClientService(settings);
                var response = client.KeywordSearch("LM2904M").Result;

                // In order to pretty print the json object we need to do the following
                jsonFormatted = JToken.Parse(response).ToString(Formatting.Indented);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(jsonFormatted);
        }