예제 #1
0
        private async void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            Text = e.Url.AbsoluteUri;
            var path = e.Url.AbsoluteUri;

            if (path.StartsWith(ConfigAPI.App_redirect))
            {
                if (string.IsNullOrEmpty(ConfigAPI.client_secret))
                {
                    return;
                }

                const string code_str = "?code=";
                var          i        = path.IndexOf(code_str);
                if (i < 0)
                {
                    return;
                }

                string code = path.Substring(i + code_str.Length, path.IndexOf('&', i) - i - code_str.Length);
                await GetAuthorizationCode(code, ct_soruce.Token);

                if (key != null && key.access_token != "")
                {
                    webBrowser1.Navigate(ConfigAPI.LoginSuccess);
                    timer1.Enabled = true;
                }
            }
            if (path.StartsWith(ConfigAPI.App_GetToken))
            {
                try
                {
                    var body = webBrowser1.DocumentText;
                    var i    = body.IndexOf("{");
                    var j    = body.IndexOf("}");
                    if (i < 0 || j < 0)
                    {
                        return;
                    }

                    key = AmazonDrive.ParseAuthResponse(body.Substring(i, j - i));
                    // Save refresh_token
                    server.Refresh_Token = key.refresh_token;
                }
                catch (Exception ex)
                {
                    error_str = ex.ToString();
                    System.Diagnostics.Debug.WriteLine(error_str);
                }
                if (key != null && key.access_token != "")
                {
                    webBrowser1.Navigate(ConfigAPI.LoginSuccess);
                    timer1.Enabled = true;
                }
            }
        }
예제 #2
0
        static public AuthKeys ParseAuthResponse(string response)
        {
            AuthKeys key        = new AuthKeys();
            var      serializer = new DataContractJsonSerializer(typeof(Authentication_Info));

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(response)))
            {
                var data = (Authentication_Info)serializer.ReadObject(ms);
                key.access_token  = data.access_token;
                key.refresh_token = data.refresh_token;
            }
            return(key);
        }
예제 #3
0
        static public async Task <AuthKeys> RefreshAuthorizationCode(AuthKeys key, CancellationToken ct = default(CancellationToken))
        {
            string error_str;

            using (var client = new HttpClient())
            {
                try
                {
                    Log("RefreshAuthorizationCode");
                    var response = await client.PostAsync(
                        (string.IsNullOrEmpty(ConfigAPI.client_secret))?ConfigAPI.App_RefreshToken : ConfigAPI.AmazonAPI_token,
                        new FormUrlEncodedContent(new Dictionary <string, string> {
                        { "grant_type", "refresh_token" },
                        { "refresh_token", key.refresh_token },
                        { "client_id", ConfigAPI.client_id },
                        { "client_secret", ConfigAPI.client_secret },
                    }),
                        ct
                        ).ConfigureAwait(false);

                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    key = ParseAuthResponse(responseBody);
                }
                catch (HttpRequestException ex)
                {
                    error_str = ex.Message;
                    System.Diagnostics.Debug.WriteLine(error_str);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    error_str = ex.ToString();
                    System.Diagnostics.Debug.WriteLine(error_str);
                }
            }
            return(key);
        }
예제 #4
0
        private async Task GetAuthorizationCode(string access_code, CancellationToken ct = default(CancellationToken))
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync(
                        ConfigAPI.AmazonAPI_token,
                        new FormUrlEncodedContent(new Dictionary <string, string> {
                        { "grant_type", "authorization_code" },
                        { "code", access_code },
                        { "client_id", ConfigAPI.client_id },
                        { "client_secret", ConfigAPI.client_secret },
                        { "redirect_uri", Uri.EscapeUriString(ConfigAPI.App_redirect) },
                    }),
                        ct
                        );

                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();

                    // Above three lines can be replaced with new helper method in following line
                    // string body = await client.GetStringAsync(uri);
                    key = AmazonDrive.ParseAuthResponse(responseBody);

                    // Save refresh_token
                    server.Refresh_Token = key.refresh_token;
                }
                catch (HttpRequestException ex)
                {
                    error_str = ex.Message;
                    System.Diagnostics.Debug.WriteLine(error_str);
                }
                catch (Exception ex)
                {
                    error_str = ex.ToString();
                    System.Diagnostics.Debug.WriteLine(error_str);
                }
            }
        }
예제 #5
0
        /// <summary>
        /// make sure access_token
        /// </summary>
        /// <param name="ct">CancellationToken</param>
        /// <returns>true: access_token is refreshed. false: not refreshed(fresh key or auth error)</returns>
        public async Task <bool> EnsureToken(CancellationToken ct = default(CancellationToken))
        {
            if (DateTime.Now - AuthTimer < TimeSpan.FromMinutes(50))
            {
                return(false);
            }
            var retry = 5;

            while (retry-- > 0)
            {
                ct.ThrowIfCancellationRequested();
                Auth = await RefreshAuthorizationCode(Auth, ct).ConfigureAwait(false);
                await EnsureEndpoint(ct).ConfigureAwait(false);

                if (await GetAccountInfo(ct).ConfigureAwait(false))
                {
                    AuthTimer = DateTime.Now;
                    return(true);
                }
                await Task.Delay(1000, ct).ConfigureAwait(false);
            }
            return(false);
        }