Пример #1
0
        private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (!e.Url.AbsoluteUri.ToString().StartsWith(redirectURI.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            try {
                OAuth2Response response = DropboxOAuth2Helper.ParseTokenFragment(e.Url);

                if (response.State != DropBoxOAuth2State)
                {
                    return;
                }

                this.AccessToken = response.AccessToken;
                this.Uid         = response.Uid;
                this.Result      = true;

                appClosing = true;
            } catch (ArgumentException ae) {
            } finally {
                //e.Cancel = true;
                this.Close();
            }
        }
Пример #2
0
 public void GetAuthTokens(Uri uri)
 {
     if (uri != null)
     {
         if (!uri.ToString().StartsWith(_redirectUri, StringComparison.OrdinalIgnoreCase))
         {
             // we need to ignore all navigation that isn't to the redirect uri.
             TestMessage = "Waiting for user details...";
             return;
         }
         Testing = false;
         if (!uri.ToString().Equals(_redirectUri, StringComparison.OrdinalIgnoreCase))
         {
             OAuth2Response result = null;
             try
             {
                 result = DropboxOAuth2Helper.ParseTokenFragment(uri);
             }
             catch (ArgumentException e)
             {
                 Dev2Logger.Warn(e.Message, "Warewolf Warn");
             }
             AuthenticationFailed(uri, result);
         }
     }
 }
        private void WebBrowser_OnNavigating(object sender, NavigatingCancelEventArgs e)
        {
            if (!e.Uri.ToString().StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }

            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != this.oauth2State)
                {
                    // The state in the response doesn't match the state in the request.
                    return;
                }

                this.AccessToken = result.AccessToken;
                this.Uid         = result.Uid;
            }
            catch (ArgumentException)
            {
                // There was an error in the URI passed to ParseTokenFragment
            }
            finally
            {
                e.Cancel = true;
                this.Close();
            }
        }
Пример #4
0
        private void Browser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (!e.Uri.AbsoluteUri.ToString().StartsWith(RedirectUri.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }


            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != DBoauth2State)
                {
                    return;
                }

                this.AccessToken = result.AccessToken;
                this.Uid         = result.Uid;
                this.Result      = true;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message);
            }

            finally
            {
                e.Cancel = true;
                this.Close();
            }
        }
        private void BrowserNavigating(object sender, NavigatingCancelEventArgs e)
        {
            // Shamelessly taken from this example: https://github.com/dropbox/dropbox-sdk-dotnet/blob/master/dropbox-sdk-dotnet/Examples/SimpleTest/LoginForm.xaml.cs
            if (!e.Uri.ToString().StartsWith(redirectUri.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                haveResult = true;
                return;
            }

            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != oAuth2State)
                {
                    // The state in the response doesn't match the state in the request.
                    haveResult = true;
                    return;
                }

                accessToken = result.AccessToken;
            }
            catch (ArgumentException)
            {
                // There was an error in the URI passed to ParseTokenFragment
            }
            finally
            {
                e.Cancel = true;
            }

            haveResult = true;
            Close();
        }
Пример #6
0
        private async void WebViewOnNavigating(object sender, WebNavigatingEventArgs e)
        {
            if (!e.Url.StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }

            try
            {
                var result = DropboxOAuth2Helper.ParseTokenFragment(new Uri(e.Url));

                if (result.State != this.oauth2State)
                {
                    return;
                }

                this.AccessToken = result.AccessToken;

                await SaveDropboxToken(this.AccessToken);
                this.OnAuthenticated?.Invoke();
            }
            catch (ArgumentException)
            {
                // There was an error in the URI passed to ParseTokenFragment
            }
            finally
            {
                e.Cancel = true;
                await Application.Current.MainPage.Navigation.PopModalAsync();
            }
        }
Пример #7
0
 // Ergebnis auswerten
 private async void ProcessResult(WebAuthenticationResult result)
 {
     try
     {
         var response = DropboxOAuth2Helper.ParseTokenFragment(new Uri(result.ResponseData));
         dropboxToken = response.AccessToken;
     }
     catch { }
 }
Пример #8
0
        public void GetAuthTokens(Uri uri)
        {
            if (uri != null)
            {
                if (!uri.ToString().StartsWith(_redirectUri, StringComparison.OrdinalIgnoreCase))
                {
                    // we need to ignore all navigation that isn't to the redirect uri.
                    TestMessage = "Waiting for user details...";
                    return;
                }
                Testing = false;
                if (!uri.ToString().Equals(_redirectUri, StringComparison.OrdinalIgnoreCase))
                {
                    OAuth2Response result = null;
                    try
                    {
                        result = DropboxOAuth2Helper.ParseTokenFragment(uri);
                    }
                    catch (ArgumentException)
                    {
                    }

                    if (result != null)
                    {
                        if (result.State != _oauth2State)
                        {
                            TestPassed       = false;
                            TestFailed       = true;
                            TestMessage      = "Authentication failed";
                            AccessToken      = string.Empty;
                            HasAuthenticated = false;
                        }
                        else
                        {
                            TestPassed       = true;
                            TestFailed       = false;
                            TestMessage      = "";
                            AccessToken      = result.AccessToken;
                            HasAuthenticated = true;
                        }
                    }
                    else
                    {
                        TestPassed       = false;
                        TestFailed       = true;
                        TestMessage      = "Authentication failed";
                        AccessToken      = string.Empty;
                        HasAuthenticated = false;

                        string errorDescription = HttpUtility.ParseQueryString(uri.ToString()).Get("error_description");

                        TestMessage = errorDescription ?? "Authentication failed";
                    }
                }
            }
        }
        public string ParseAccessToken(Uri uri)
        {
            if (IsErrorInUrl(uri))
            {
                throw new ArgumentException(nameof(uri));
            }
            // make handling if bereaer token is not reachable
            var result = DropboxOAuth2Helper.ParseTokenFragment(uri);

            return(AccessToken = result.AccessToken);
        }
Пример #10
0
        private void WebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!e.Uri.IsLoopback)
            {
                return;
            }

            Response = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);

            DialogResult = true;
            Close();
        }
Пример #11
0
        /// <summary>
        /// Validates the login attempt
        /// If successful the AccessToken is populated
        /// </summary>
        /// <param name="uri">The URL the login attempt navigated to</param>
        /// <returns>True if login successful</returns>
        internal bool Validate(Uri uri)
        {
            AccessToken = "";

            OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(uri);

            if (result.State == _Oauth2State)
            {
                AccessToken = result.AccessToken;
                return(true);
            }

            return(false);
        }
Пример #12
0
        private void webBrowser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            try
            {
                this.Result = false;

                #region Dropbox

                if (AuthType == AuthenticateTypeList.Dropbox)
                {
                    if (!e.Uri.ToString().StartsWith(db_RedirectUri, StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }

                    OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                    if (result.State != this.db_Oauth2State)
                    {
                        return;
                    }

                    this.db_AccessToken = result.AccessToken;
                    this.db_UserId      = result.Uid;
                    this.Result         = true;

                    var httpClient = new HttpClient()
                    {
                        Timeout = TimeSpan.FromMinutes(20)
                    };

                    var config = new DropboxClientConfig("SimpleTestApp")
                    {
                        HttpClient = httpClient
                    };

                    db_Client = new DropboxClient(this.db_AccessToken, config);

                    this.Close();
                }

                #endregion Dropbox
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                this.Result = false;
                this.Close();
            }
        }
Пример #13
0
        private async Task <OAuth2Response> HandleJSRedirect(HttpListener http)
        {
            var context = await http.GetContextAsync();

            while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
            {
                context = await http.GetContextAsync();
            }

            var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]);

            var result = DropboxOAuth2Helper.ParseTokenFragment(redirectUri);

            return(result);
        }
Пример #14
0
        private OAuth2Response HandleJSRedirect(HttpListener http)
        {
            var context = http.GetContext();

            // We only care about request to TokenRedirectUri endpoint.

            while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath)
            {
                context = http.GetContext();
            }

            var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]);

            var result = DropboxOAuth2Helper.ParseTokenFragment(redirectUri);

            return(result);
        }
        public void GetAccessToken(DropboxLoginSuccessfulMessage msg)
        {
            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(msg.RedirectUri);
                if (result.State != _oauth2State)
                {
                    throw new Exception("OAuth2 state mismatch");
                }

                _settings.Token = result.AccessToken;
                Messenger.Default.Send(new CredentialsUpdatedMessage());
            }
            catch (Exception ex)
            {
                Messenger.Default.Send(new AuthenticationErrorMessage(ex));
            }
        }
Пример #16
0
        /// <summary>
        /// Processes the result.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <exception cref="UniversalDemo.OAuthException">
        /// Raised if there was an HTTP error during the authentication process.
        /// </exception>
        /// <exception cref="UniversalDemo.OAuthUserCancelledException">
        /// Raised if the user cancelled authentication.
        /// </exception>
        private static void ProcessResult(WebAuthenticationResult result)
        {
            switch (result.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                var response = DropboxOAuth2Helper.ParseTokenFragment(
                    new Uri(result.ResponseData));
                ((App)Application.Current).AccessToken = response.AccessToken;
                break;

            case WebAuthenticationStatus.ErrorHttp:
                throw new OAuthException(result.ResponseErrorDetail);

            case WebAuthenticationStatus.UserCancel:
            default:
                throw new OAuthUserCancelledException();
            }
        }
 public void HandleNavigating(HandleNavigation e)
 {
     if (!e.Uri.ToString().StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
     {
         return;
     }
     try
     {
         var result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
         if (result.State != this.oauth2State)
         {
             return;
         }
         this.eventAggregator.Publish(new DropboxSignInSuccessfull(result));
     }
     finally
     {
         e.Cancel = true;
     }
 }
Пример #18
0
 private void W_LoadError(object sender, CefSharp.LoadErrorEventArgs e)
 {
     if (e.FailedUrl.StartsWith(RedirectUri, StringComparison.InvariantCultureIgnoreCase))
     {
         try
         {
             OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(new Uri(e.FailedUrl));
             if (result.State == oauth2State)
             {
                 w.Invoke((MethodInvoker)(() => w.Hide()));
                 Properties.Settings.Default.AccessToken = result.AccessToken;
                 Properties.Settings.Default.Save();
                 Invoke((MethodInvoker)(() => InitClient(result.AccessToken)));
             }
         }
         catch (ArgumentException)
         {
             MessageBox.Show("There was an error");
         }
     }
 }
Пример #19
0
        private async Task ProcessResult(WebAuthenticationResult result)
        {
            switch (result.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
            {
                try
                {
                    ProgressRing.IsActive = true;
                    var response = DropboxOAuth2Helper.ParseTokenFragment(new Uri(result.ResponseData));
                    Helpers.Settings.DropboxAccessToken = response.AccessToken;
                    if (!_checkDropboxFileExist)
                    {
                        MainBudget.Instance.OnCloudStorageConnected();
                    }
                    else if (await HasDropboxData())
                    {
                        MainBudget.Instance.OnCloudStorageConnected();
                    }
                    else
                    {
                        ProgressRing.IsActive = false;
                        ShowToastNotification("HomeBudget", "Dropbox data not found");
                    }
                }
                catch (Exception exc)
                {
                    var msg = exc.Message;
                }
            }
            break;

                /*case WebAuthenticationStatus.ErrorHttp:
                 *  throw new OAuthException(result.ResponseErrorDetail);
                 *
                 * case WebAuthenticationStatus.UserCancel:
                 * default:
                 *  throw new OAuthUserCancelledException();*/
            }
        }
Пример #20
0
        /// <summary>
        ///     Wird aufgerufen nachdem der Benutzer den Zugriff authorisiert hat
        ///     Die ist der 2. Schritt
        /// </summary>
        /// <returns></returns>
        public Member GetUserAuthentication(Uri requestUri)
        {
            var result = DropboxOAuth2Helper.ParseTokenFragment(requestUri);

            var isNew  = false;
            var access = CurrentMember.StorageAccesses.FirstOrDefault(
                s => s.Type == StorageProviderType.Dropbox && s.MemberId == CurrentMember.Id);

            if (access == null)
            {
                access = new MemberStorageAccess
                {
                    Type     = StorageProviderType.Dropbox,
                    MemberId = CurrentMember.Id,
                };

                isNew = true;
            }

            access.Token  = result.AccessToken;
            access.UserId = result.Uid;

            if (isNew)
            {
                Repository.Add(access);
                CurrentMember.StorageAccessType = StorageProviderType.Dropbox;
                Repository.Update(CurrentMember);
            }
            else
            {
                Repository.Update(access);
            }
            _access = access;
            CheckFolderStructure();

            CurrentMember.StorageAccesses = new List <MemberStorageAccess> {
                access
            };
            return(CurrentMember);
        }
        private void BrowserNavigating(object sender, NavigatingCancelEventArgs e)
        {
            if (!e.Uri.ToString().StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }

            try
            {
                OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Uri);
                if (result.State != this.oauth2State)
                {
                    return;
                }

                this.AccessToken             = result.AccessToken;
                this.Uid                     = result.Uid;
                this.Result                  = true;
                Settings.Default.AccessToken = AccessToken;
                Settings.Default.Uid         = Uid;
                Settings.Default.Save();
                var task = Task.Run((Func <Task>)LoginForm.Run);
                task.Wait();
                var task2 = Task.Run((Func <Task>)HomePage.Run);
                task2.Wait();
                this.RefreshEvent(this, new EventArgs());
            }
            catch (ArgumentException ers)
            {
                // There was an error in the URI passed to ParseTokenFragment
                MessageBox.Show("リンクに問題が発生しました。\n\n" + ers.Message.Replace("Invalid OAuth 2.0 response, missing access_token and/or uid.", "無効なOAuth 2.0レスポンスです。access_tokenまたはuidがありません。\nリクエストを許可してください。"), "DropBoxリンク", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                e.Cancel = true;
                this.Close();
            }
        }
Пример #22
0
        public Task <bool> Claim(Uri uri, string documentTitle)
        {
            var cs = new TaskCompletionSource <bool>();

            try
            {
                var result = DropboxOAuth2Helper.ParseTokenFragment(uri);
                if (result.State != _state)
                {
                    // The state in the response doesn't match the state in the request.
                    cs.SetResult(false);
                    return(cs.Task);
                }

                _oauthResponse = result;
                cs.SetResult(true);
                return(cs.Task);
            }
            catch (Exception ex)
            {
                cs.SetException(ex);
                return(cs.Task);
            }
        }
Пример #23
0
        /// <inheritdoc/>
        public async Task <bool> TryAuthenticateWithUiAsync(ICloudAuthentication authentication)
        {
            var oauth2State       = Guid.NewGuid().ToString("N");
            var authenticationUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, SecurityHelper.ToUnsecureString(_appKey), new Uri(SecurityHelper.ToUnsecureString(_redirectUri)), oauth2State);

            var authenticationResult = await authentication.AuthenticateAsync(authenticationUri.ToString(), SecurityHelper.ToUnsecureString(_redirectUri));

            if (authenticationResult.IsCanceled)
            {
                IsAuthenticated = false;
                return(IsAuthenticated);
            }

            var result = DropboxOAuth2Helper.ParseTokenFragment(authenticationResult.RedirectedUri);

            if (result.State != oauth2State)
            {
                IsAuthenticated = false;
                return(IsAuthenticated);
            }

            TokenProvider.SetToken("AccessToken", SecurityHelper.EncryptString(SecurityHelper.ToSecureString(result.AccessToken)));
            return(await TryAuthenticateAsync());
        }
Пример #24
0
        private static DropboxCredentials ParseDropboxUri()
        {
            var oauth2State = Guid.NewGuid().ToString("N");
            var authUri = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Token, ApiConfig.DropboxClientId, new Uri(RedirectUri), state: oauth2State)
                .ToString();

            Console.WriteLine("    We will open browser with the DropBox sign in url.");
            Console.WriteLine("    Please login to your dropbox account to grant Virgil Sync access to it.");
            Console.WriteLine("    When you'l finish, please copy final url in your browser tab. It should starts with " + RedirectUri);

            Process.Start(authUri);
            Console.Write("    Url: ");
            var uri = Console.ReadLine();

            try
            {
                var result = DropboxOAuth2Helper.ParseTokenFragment(new Uri(uri));

                if (result.State != oauth2State)
                {
                    throw new Exception("OAuth state was changed");
                }

                return new DropboxCredentials
                {
                    AccessToken = result.AccessToken,
                    UserId = result.Uid,
                };
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
Пример #25
0
        public void SetAccessToken(Uri result)
        {
            OAuth2Response result1 = DropboxOAuth2Helper.ParseTokenFragment(result);

            this.AccessToken = result1.AccessToken;
        }
Пример #26
0
        public async Task <bool> SignInAsync(bool interactive, CancellationToken cancellationToken)
        {
            using (await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false))
            {
                try
                {
                    if (await IsAuthenticatedAsync().ConfigureAwait(false))
                    {
                        // Already authenticated.
                        _logger.LogEvent(SignInEvent, "Already signed in");
                        return(true);
                    }

                    string accessToken = string.Empty;

                    try
                    {
                        _logger.LogEvent(SignInEvent, "Sign in silently");
                        accessToken = await SilentAuthenticateAsync(cancellationToken).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        if (!interactive)
                        {
                            _logger.LogFault(SignInSilentlyFaultEvent, "Unable to authenticate to DropBox silently.", ex);
                            await SignOutInternalAsync().ConfigureAwait(false);
                        }
                    }

                    if (interactive && string.IsNullOrEmpty(accessToken))
                    {
                        try
                        {
                            _oauth2State = Guid.NewGuid().ToString("N");

                            Uri autorizationUri = DropboxOAuth2Helper.GetAuthorizeUri(
                                OAuthResponseType.Token,
                                ServicesKeys.DropBoxAppKey,
                                new Uri(ServicesKeys.DropBoxRedirectUri),
                                state: _oauth2State);

                            WebAuthenticationResult authenticationResult = null;

                            await TaskHelper.RunOnUIThreadAsync(async() =>
                            {
                                // WebAuthenticationBroker.AuthenticateAsync should run on the UI thread.
                                _logger.LogEvent(SignInEvent, "Sign in with interaction");
                                authenticationResult
                                    = await WebAuthenticationBroker.AuthenticateAsync(
                                          WebAuthenticationOptions.None,
                                          autorizationUri,
                                          new Uri(ServicesKeys.DropBoxRedirectUri));
                            }).ConfigureAwait(false);

                            cancellationToken.ThrowIfCancellationRequested();

                            if (authenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                            {
                                accessToken = DropboxOAuth2Helper.ParseTokenFragment(new Uri(authenticationResult.ResponseData)).AccessToken;
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogFault(SignInWithInteractionFaultEvent, "Unable to authenticate to OneDrive with interaction.", ex);
                            await SignOutInternalAsync().ConfigureAwait(false);
                        }
                    }

                    if (!string.IsNullOrEmpty(accessToken))
                    {
                        // Authentication seemed to work.
                        _settingsProvider.SetSetting(DropBoxAccessToken, accessToken);
                        _dropboxClient?.Dispose();
                        _dropboxClient = new DropboxClient(accessToken, new DropboxClientConfig(UserAgent));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogFault(SignInFaultEvent, "Unable to sign in to DropBox.", ex);
                }

                bool isAuthenticated = await IsAuthenticatedAsync().ConfigureAwait(false);

                if (isAuthenticated)
                {
                    _logger.LogEvent(SignInEvent, "Signed in successfully");
                }
                else
                {
                    _logger.LogEvent(SignInFaultEvent, "It seemed to failed without exception.");
                }

                return(isAuthenticated);
            }
        }