コード例 #1
0
        public void ExchangeAuthorizationForToken()
        {
            var http             = new Mock <HttpService>(null, new RequestBuilder());
            var mockRestResponse = new Mock <RestResponse>();
            var oauthService     = new OAuth2Service(http.Object);

            mockRestResponse.Object.Content =
                new FixtureLoader("v2", "oauthAccessToken/success.http")
                .ExtractJsonPayload();

            SetupMockHttpService(http, mockRestResponse);

            _authArguments = new Dictionary <OAuthParams, string>
            {
                { OAuthParams.ClientId, "id" },
                { OAuthParams.ClientSecret, "secret" },
                { OAuthParams.Code, "code" },
                { OAuthParams.State, "state" },
                { OAuthParams.RedirectUri, "/redirectUri" }
            };
            var accessTokenData =
                oauthService.ExchangeAuthorizationForToken(_authArguments);

            Assert.AreEqual("zKQ7OLqF5N1gylcJweA9WodA000BUNJD",
                            accessTokenData.AccessToken);
        }
コード例 #2
0
 public DigikeyApi(OAuth2Service oAuth2Service, string apiUrl, ICredentialService credentialService, IHttpContextAccessor httpContextAccessor)
 {
     _oAuth2Service       = oAuth2Service;
     _apiUrl              = apiUrl;
     _credentialService   = credentialService;
     _httpContextAccessor = httpContextAccessor;
     _client              = new HttpClient();
 }
コード例 #3
0
        public ActionResult GoogleCallback(string code)
        {
            OAuth2Service.GetToken(code);
            var account = OAuth2Service.GetProfileInfo();

            CurrentUser.Info = account;

            return(RedirectToAction("Index"));
        }
コード例 #4
0
        public MockDnsimpleClient(string fixture)
        {
            Fixture = fixture;

            Accounts  = new AccountsService(this);
            Domains   = new DomainsService(this);
            Http      = new MockHttpService("v2", Fixture, BaseUrl);
            Identity  = new IdentityService(this);
            OAuth     = new OAuth2Service(Http);
            Registrar = new RegistrarService(this);
            Zones     = new ZonesService(this);
        }
コード例 #5
0
ファイル: DNSimple.cs プロジェクト: san983/dnsimple-csharp
 /// <summary>
 /// Initializes all the services offered by the current version of
 /// this API.
 /// </summary>
 /// <see cref="IdentityService"/>
 /// <see cref="HttpService"/>
 /// <see cref="OAuth2Service"/>
 private void InitializeServices()
 {
     Accounts     = new AccountsService(this);
     Certificates = new CertificatesService(this);
     Domains      = new DomainsService(this);
     Http         = new HttpService(RestClientWrapper.RestClient,
                                    new RequestBuilder());
     Identity  = new IdentityService(this);
     OAuth     = new OAuth2Service(Http);
     Registrar = new RegistrarService(this);
     Tlds      = new TldsService(this);
     Zones     = new ZonesService(this);
 }
コード例 #6
0
        // GET: Auth2
        public ActionResult Index()
        {
            string code = Request.QueryString["code"];

            if (!string.IsNullOrEmpty(code))
            {
                LogService.Write("收到用户授权code:" + code);
                UserAccessToken t = OAuth2Service.get_accesstoken_bycode(code);

                LogService.Write("获取到了用户accesstoken:" + t.access_token + ", refresh token:" + t.refresh_token + ", openid=" + t.openid + ", scope:" + t.scope + ", expires_in:" + t.expires_in);
                return(View());
            }
            return(Content("NO CODE"));
        }
コード例 #7
0
 /// <summary>
 /// Initializes all the services offered by the current version of
 /// this API.
 /// </summary>
 /// <see cref="IdentityService"/>
 /// <see cref="HttpService"/>
 /// <see cref="OAuth2Service"/>
 private void InitializeServices()
 {
     Http              = new HttpService(RestClientWrapper.RestClient, new RequestBuilder());
     Accounts          = new AccountsService(this);
     Certificates      = new CertificatesService(this);
     Contacts          = new ContactsService(this);
     Domains           = new DomainsService(this);
     Identity          = new IdentityService(this);
     OAuth             = new OAuth2Service(Http);
     Registrar         = new RegistrarService(this);
     Services          = new ServicesService(this);
     Tlds              = new TldsService(this);
     Templates         = new TemplatesService(this);
     VanityNameServers = new VanityNameServersService(this);
     Webhooks          = new WebhooksService(this);
     Zones             = new ZonesService(this);
 }
コード例 #8
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;
            }
        }
コード例 #9
0
        public MockDnsimpleClient(string fixture)
        {
            Fixture   = fixture;
            UserAgent = "Testing user agent";

            Accounts          = new AccountsService(this);
            Certificates      = new CertificatesService(this);
            Contacts          = new ContactsService(this);
            Domains           = new DomainsService(this);
            Http              = new MockHttpService("v2", Fixture, BaseUrl);
            Identity          = new IdentityService(this);
            OAuth             = new OAuth2Service(Http);
            Registrar         = new RegistrarService(this);
            Services          = new ServicesService(this);
            Tlds              = new TldsService(this);
            Templates         = new TemplatesService(this);
            VanityNameServers = new VanityNameServersService(this);
            Webhooks          = new WebhooksService(this);
            Zones             = new ZonesService(this);
        }
コード例 #10
0
        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;
            }
        }
コード例 #11
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);
        }
コード例 #12
0
        public ActionResult GoogleRedirect()
        {
            var url = OAuth2Service.OAuth2Url();

            return(Redirect(url.AbsoluteUri));
        }
コード例 #13
0
 public static void UpdateOAuth2Service(ApiClientSettings clientSettings)
 {
     _oAuth2Service = new OAuth2Service(clientSettings);
 }
コード例 #14
0
 public OAuth2Controller(IOptions <AuthOptions> options,
                         OAuth2Service authService)
 {
     _options     = options.Value;
     _authService = authService;
 }
コード例 #15
0
 public AuthorizationController(ILogger <AuthorizationController> logger, OAuth2Service oAuth2Service, ICredentialService credentialService)
 {
     _logger            = logger;
     _oAuth2Service     = oAuth2Service;
     _credentialService = credentialService;
 }