Esempio n. 1
0
        // GET: /IntegratedOptions/Auth
        public async Task <ActionResult> Auth(string code, string state)
        {
            try
            {
                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    appKey,
                    appSecret,
                    RedirectUri);

                using (var dbx = new DropboxClient(response.AccessToken))
                {
                    var full = await dbx.Users.GetCurrentAccountAsync();

                    var list = await dbx.Files.ListFolderAsync(string.Empty);

                    var checkexisting = db.CoDropbox.Where(p => p.SiteCoID == siteusercompanyid).FirstOrDefault();
                    if (checkexisting == null)
                    {
                        db.InsertDropbox(base.siteusercompanyid, appKey, appSecret, Encoding.ASCII.GetBytes(response.AccessToken), full.Email, "", DateTime.UtcNow.Date, RedirectUri);
                        db.SaveChanges();
                    }
                }
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                var message = string.Format(
                    "code: {0}\nAppKey: {1}\nAppSecret: {2}\nRedirectUri: {3}\nException : {4}",
                    code,
                    appKey,
                    appSecret,
                    this.RedirectUri,
                    e);
                return(RedirectToAction("error"));
            }
        }
        private async void WebView_Navigated(object sender, WebNavigatedEventArgs 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 (Exception ex)
            {
                // There was an error in the URI passed to ParseTokenFragment
            }
            finally
            {
                //e.Cancel = true;
                if (Application.Current.MainPage.Navigation.ModalStack.Count > 0)
                {
                    await Application.Current.MainPage.Navigation.PopModalAsync();
                }
            }
        }
Esempio n. 3
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;
            }
        }
Esempio n. 4
0
        /// <summary>
        ///     <para>Runs the Dropbox OAuth authorization process if not yet authenticated.</para>
        ///     <para>Upon completion <seealso cref="OnAuthenticated"/> is called</para>
        /// </summary>
        /// <returns>An asynchronous task.</returns>
        public async Task Authorize()
        {
            if (string.IsNullOrWhiteSpace(this.AccessToken) == false)
            {
                // Already authorized
                this.OnAuthenticated?.Invoke();
                return;
            }

            if (this.GetAccessTokenFromSettings())
            {
                // Found token and set AccessToken 
                return;
            }

            // Run Dropbox authentication
            this.oauth2State = Guid.NewGuid().ToString("N");
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, "zgomjzxhw2j7lvq", new Uri("http://localhost/"), this.oauth2State);
            Console.WriteLine("URI ======> {0}", authorizeUri);
            var webView = new WebView { Source = new UrlWebViewSource { Url = authorizeUri.AbsoluteUri } };
            webView.Navigating += this.WebViewOnNavigating;
            var contentPage = new ContentPage { Content = webView };
            await Application.Current.MainPage.Navigation.PushModalAsync(contentPage);
        }
Esempio n. 5
0
        public async Task <ActionResult> Auth(string code, string state)
        {
            try
            {
                if (this.currentUser.ConnectState != state)
                {
                    this.Flash("There was an error connecting to Dropbox.");
                    return(this.RedirectToAction("Index"));
                }

                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    MvcApplication.AppKey,
                    MvcApplication.AppSecret,
                    this.RedirectUri);

                this.currentUser.DropboxAccessToken = response.AccessToken;
                this.currentUser.ConnectState       = string.Empty;
                await this.store.SaveChangesAsync();

                this.Flash("This account has been connected to Dropbox.", FlashLevel.Success);
                return(RedirectToAction("Profile"));
            }
            catch (Exception e)
            {
                var message = string.Format(
                    "code: {0}\nAppKey: {1}\nAppSecret: {2}\nRedirectUri: {3}\nException : {4}",
                    code,
                    MvcApplication.AppKey,
                    MvcApplication.AppSecret,
                    this.RedirectUri,
                    e);
                this.Flash(message, FlashLevel.Danger);
                return(RedirectToAction("Profile"));
            }
        }
Esempio n. 6
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);
            }
        }
Esempio n. 7
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());
        }
Esempio n. 8
0
        /// <summary>
        /// Acquires a dropbox access token and saves it to the default settings for the app.
        /// <para>
        /// This fetches the access token from the applications settings, if it is not found there
        /// (or if the user chooses to reset the settings) then the UI in <see cref="LoginForm"/> is
        /// displayed to authorize the user.
        /// </para>
        /// </summary>
        /// <returns>A valid uid if a token was acquired or null.</returns>
        private async Task <string> AcquireAccessToken(string[] scopeList, IncludeGrantedScopes includeGrantedScopes)
        {
            Console.Write("Reset settings (Y/N) ");
            if (Console.ReadKey().Key == ConsoleKey.Y)
            {
                Settings.Default.Reset();
            }
            Console.WriteLine();

            var accessToken  = Settings.Default.AccessToken;
            var refreshToken = Settings.Default.RefreshToken;

            if (string.IsNullOrEmpty(accessToken))
            {
                try
                {
                    Console.WriteLine("Waiting for credentials.");
                    var state        = Guid.NewGuid().ToString("N");
                    var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, ApiKey, RedirectUri, state: state, tokenAccessType: TokenAccessType.Offline, scopeList: scopeList, includeGrantedScopes: includeGrantedScopes);
                    var http         = new HttpListener();
                    http.Prefixes.Add(LoopbackHost);

                    http.Start();

                    System.Diagnostics.Process.Start(authorizeUri.ToString());

                    // Handle OAuth redirect and send URL fragment to local server using JS.
                    await HandleOAuth2Redirect(http);

                    // Handle redirect from JS and process OAuth response.
                    var redirectUri = await HandleJSRedirect(http);

                    Console.WriteLine("Exchanging code for token");
                    var tokenResult = await DropboxOAuth2Helper.ProcessCodeFlowAsync(redirectUri, ApiKey, ApiSecret, RedirectUri.ToString(), state);

                    Console.WriteLine("Finished Exchanging Code for Token");
                    // Bring console window to the front.
                    SetForegroundWindow(GetConsoleWindow());
                    accessToken  = tokenResult.AccessToken;
                    refreshToken = tokenResult.RefreshToken;
                    var uid = tokenResult.Uid;
                    Console.WriteLine("Uid: {0}", uid);
                    Console.WriteLine("AccessToken: {0}", accessToken);
                    if (tokenResult.RefreshToken != null)
                    {
                        Console.WriteLine("RefreshToken: {0}", refreshToken);
                        Settings.Default.RefreshToken = refreshToken;
                    }
                    if (tokenResult.ExpiresAt != null)
                    {
                        Console.WriteLine("ExpiresAt: {0}", tokenResult.ExpiresAt);
                    }
                    if (tokenResult.ScopeList != null)
                    {
                        Console.WriteLine("Scopes: {0}", String.Join(" ", tokenResult.ScopeList));
                    }
                    Settings.Default.AccessToken = accessToken;
                    Settings.Default.Uid         = uid;
                    Settings.Default.Save();
                    http.Stop();
                    return(uid);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                    return(null);
                }
            }

            return(null);
        }
 public Uri GetAuthorizeUri(string appKey, string redirectUri)
 {
     return(DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, appKey, new Uri(redirectUri), string.Empty));
 }
Esempio n. 10
0
 /// <summary>
 ///     Liefert die URL für die Authorisierung der Anwendung zurück
 ///     Dies ist der 1. Schritt
 /// </summary>
 /// <param name="callbackUrl">Die Url, die nach der Authorisierung aufgerufen werden soll</param>
 /// <param name="state">GUID zur Wiedererkennung des Requests</param>
 /// <returns>Die Url für die Authorisierung</returns>
 public string GetAuthorizeUrl(string callbackUrl, string state)
 {
     return(DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, Startup.DropboxAppKey, new Uri(callbackUrl), state).ToString());
 }
Esempio n. 11
0
        /// <summary>
        /// Attempts to connect to a users dropbox. First, the dropbox_file_converter_config.json file will be checked for an access key which will be used to attempt to gain access to a users Dropbox. If this fails for whatever reason, then the user will go through Dropbox's OAuth2 procedure for obtaining an access key.
        /// </summary>
        public void ConnectToDropbox(ref JsonValue config)
        {
            bool connected = false;

            while (!connected)
            {
                //Attempt to load a previously saved access key from the config file
                string accessKey = (string)config["access_key"];

                //Attempt to start a Dropbox database connection with the access key
                try
                {
                    //If the loaded access key is not an empty string, try to establish a dropbox connection with it
                    if (accessKey != string.Empty)
                    {
                        //Establish the dropbox connection
                        Console.WriteLine("Attempting dropbox connection...");
                        dbx = new DropboxClient(accessKey);

                        //Check if the previously established connection is valid by making a small request of the users account name
                        var getAccount = Task.Run((Func <Task <Dropbox.Api.Users.FullAccount> >)dbx.Users.GetCurrentAccountAsync);
                        getAccount.Wait();
                        Console.WriteLine("Dropbox connection established. Connected as {0}!\n", getAccount.Result.Name.DisplayName);
                        connected = true;
                    }
                    else
                    {
                        Console.WriteLine("No access key found for user. Attempting to obtain one...\n");
                    }
                }
                catch
                {
                    Console.WriteLine("Access key from config JSON not valid. Will have to obtain another...\n");
                }

                try
                {
                    //Use Dropbox's OAuth2 feature to authenticate new users, if the user does not have a valid access key
                    if (!connected)
                    {
                        //Use the dropbox app key to redirect the user to a webpage, giving them the choice to allow this app to access their Dropbox
                        Console.WriteLine("Opening authorisation webpage...");
                        Uri webpage = DropboxOAuth2Helper.GetAuthorizeUri(dropboxAppKey);
                        System.Diagnostics.Process.Start(webpage.ToString());

                        //If the user chooses to allow the app to access their Dropbox, then they will be given a key to paste back into this app
                        Console.WriteLine("Please paste in the key provided to you below:");
                        string key = Console.ReadLine();
                        Console.WriteLine("\nThank you, attempting dropbox connection now...");

                        //Use this key in conjunction with the dropbox app secret to obtain an access key that can be used to access the users Dropbox
                        var getAccessKeyTask = Task.Run(() => DropboxOAuth2Helper.ProcessCodeFlowAsync(key, dropboxAppKey, dropboxAppSecret));
                        getAccessKeyTask.Wait();

                        //Save the new access key to the config JSON, format it to make it more human readable, and save it back to the app's root
                        config["access_key"] = getAccessKeyTask.Result.AccessToken.ToString();
                        File.WriteAllText("dropbox_file_converter_config.json", config.ToString().Replace("{", "{" + Environment.NewLine).Replace(",", "," + Environment.NewLine));
                    }
                }
                catch
                {
                    Console.WriteLine("Something went wrong trying to obtain an access token. Program will now close...");
                    Console.ReadLine();
                    Environment.Exit(0);
                }
            }
        }
 public async Task Initialize()
 {
     _state = Guid.NewGuid().ToString("N");
     this.AuthorizationUrl = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token,
                                                                 DropboxHelper.DropboxClientId, RedirectionUrl, _state);
 }
Esempio n. 13
0
        public DropboxAuthDialog()
        {
            AuthorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, "zv9bia97vj4w1iw", new Uri("http://localhost/"));

            InitializeComponent();
        }
Esempio n. 14
0
        public async Task TestGetAuthorizationUri()
        {
            string clientId = "myclientid";

            string[]        redirectUris           = new[] { "", "http://127.0.0.1:52475/" };
            string[]        states                 = new[] { "", "state" };
            bool[]          forceReapproves        = new[] { false, true };
            bool[]          disableSignups         = new[] { false, true };
            string[]        requireRoles           = new[] { "", "role" };
            bool[]          forceReauthentications = new[] { false, true };
            List <String[]> scopes                 = new List <String[]>();

            scopes.Add(null);
            scopes.Add(new String[] { "files.metadata.read", "files.content.read" });
            IncludeGrantedScopes[] includeGrantedScopes = new[] { IncludeGrantedScopes.None, IncludeGrantedScopes.User, IncludeGrantedScopes.Team };

            TokenAccessType[] tokenAccessTypes = new[]
            { TokenAccessType.Legacy, TokenAccessType.Offline, TokenAccessType.Online };
            foreach (string redirectUri in redirectUris)
            {
                foreach (var state in states)
                {
                    foreach (var forceReapprove in forceReapproves)
                    {
                        foreach (var disableSignup in disableSignups)
                        {
                            foreach (var requireRole in requireRoles)
                            {
                                foreach (var forceReauthentication in forceReauthentications)
                                {
                                    foreach (var tokenAccessType in tokenAccessTypes)
                                    {
                                        foreach (var scope in scopes)
                                        {
                                            foreach (var includeGrantedScope in includeGrantedScopes)
                                            {
                                                var authUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code,
                                                                                                  clientId, redirectUri, state, forceReapprove, disableSignup,
                                                                                                  requireRole, forceReauthentication, tokenAccessType, scope, includeGrantedScope).ToString();

                                                Assert.IsTrue(authUri.StartsWith("https://www.dropbox.com/oauth2/authorize"));
                                                Assert.IsTrue(authUri.Contains("response_type=code"));
                                                Assert.IsTrue(authUri.Contains("client_id=" + clientId));

                                                if (String.IsNullOrWhiteSpace(state))
                                                {
                                                    Assert.IsFalse(authUri.Contains("&state="));
                                                }
                                                else
                                                {
                                                    Assert.IsTrue(authUri.Contains("&state=" + state));
                                                }

                                                if (String.IsNullOrWhiteSpace(redirectUri))
                                                {
                                                    Assert.IsFalse(authUri.Contains("&redirect_uri="));
                                                }
                                                else
                                                {
                                                    Assert.IsTrue(authUri.Contains("&redirect_uri=" + Uri.EscapeDataString(redirectUri)));
                                                }

                                                if (forceReapprove)
                                                {
                                                    Assert.IsTrue(authUri.Contains("&force_reapprove=true"));
                                                }
                                                else
                                                {
                                                    Assert.IsFalse(authUri.Contains("&force_reapprove="));
                                                }

                                                if (disableSignup)
                                                {
                                                    Assert.IsTrue(authUri.Contains("&disable_signup=true"));
                                                }
                                                else
                                                {
                                                    Assert.IsFalse(authUri.Contains("&disable_signup="));
                                                }

                                                if (String.IsNullOrWhiteSpace(requireRole))
                                                {
                                                    Assert.IsFalse(authUri.Contains("&require_role="));
                                                }
                                                else
                                                {
                                                    Assert.IsTrue(authUri.Contains("&require_role=" + requireRole));
                                                }

                                                if (forceReauthentication)
                                                {
                                                    Assert.IsTrue(authUri.Contains("&force_reauthentication=true"));
                                                }
                                                else
                                                {
                                                    Assert.IsFalse(authUri.Contains("&force_reauthentication="));
                                                }

                                                if (tokenAccessType != TokenAccessType.Legacy)
                                                {
                                                    Assert.IsTrue(authUri.Contains("&token_access_type=" +
                                                                                   tokenAccessType.ToString().ToLower()));
                                                }
                                                else
                                                {
                                                    Assert.IsFalse(authUri.Contains("&token_access_type="));
                                                }

                                                if (scope != null)
                                                {
                                                    Assert.IsTrue(authUri.Contains("&scope=" + String.Join(" ", scope)));
                                                }
                                                else
                                                {
                                                    Assert.IsFalse(authUri.Contains("&scope="));
                                                }

                                                if (includeGrantedScope != IncludeGrantedScopes.None)
                                                {
                                                    Assert.IsTrue(authUri.Contains("&include_granted_scopes=" +
                                                                                   includeGrantedScope.ToString().ToLower()));
                                                }
                                                else
                                                {
                                                    Assert.IsFalse(authUri.Contains("&include_granted_scopes="));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 15
0
        public async Task <HttpResponseMessage> Get(string code, string state)
        {
            using (var system = CreateRequestSystemExecutionContext())
            {
                // NOTE: In production, OAuth must be done over a secure HTTPS connection.
                if (Request.RequestUri.Scheme != "https" && !Request.RequestUri.IsLoopback)
                {
                    return(await Task.FromResult(Get("Endpoint is not HTTPS")));
                }

                // Ensure there is a state value on the response.  If there is none, stop OAuth processing and display an error.
                if (state == null)
                {
                    return(await Task.FromResult(Get(NoStateWasReturnedFromAuthenticator)));
                }

                if (code == null)
                {
                    return(await Task.FromResult(Get("No code was returned from authenticator")));
                }

                var clientId     = ConfigurationManager.AppSettings.GetValue("Providers.DropBoxClientId", (string)null);
                var clientSecret = ConfigurationManager.AppSettings.GetValue("Providers.DropBoxClientSecret", (string)null);

                if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
                {
                    throw new Exception("Could not get DropBox ClientId or ClientSecret");
                }

                var stateObject = ValidateState(system, state);

                if (stateObject == null)
                {
                    _log.Error(new { code, state }, () => NoStateFoundInCluedin);
                    return(await Task.FromResult(Get(NoStateFoundInCluedin)));
                }

                var authenticationFlow = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, clientId, clientSecret, stateObject.RedirectUrl);

                var accessToken = authenticationFlow.AccessToken;

                using (var context = CreateRequestExecutionContext(stateObject.OrganizationId))
                {
                    DeleteExistingTokenIfNotAssociatedWithDropBox(context, DropBoxConstants.ProviderId, stateObject);

                    string accountId;
                    try
                    {
                        accountId = await GetDropBoxAccountId(accessToken);
                    }
                    catch (Exception exception)
                    {
                        _log.Warn(() => "Could not add DropBox provider", exception);
                        return(Get("Could not access token store"));
                    }

                    CheckForExistingToken(context, DropBoxConstants.ProviderId, accountId, stateObject);

                    var reAuthenticated = CheckForReAuthentication(context, DropBoxConstants.ProviderId, accountId, stateObject, accessToken, null);

                    // Return to the originating page where the user triggered the sign-in
                    var response = CreateResponse(context, reAuthenticated);

                    return(response);
                }
            }
        }
Esempio n. 16
0
        public async Task Authenticate(string authCode)
        {
            OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(authCode, "unqwltt7mf1x5mh", "yehgvm5kg1qlel3", RedirectUri);

            _accessToken = response.AccessToken;
        }
 private void RetryButton_Click(object sender, System.EventArgs e)
 {
     Process.Start(DropboxOAuth2Helper.GetAuthorizeUri("jj2eyo41xn837y7", false).ToString()); //вызов страницы для подтверждения доступа и получения кода
 }
    public static void LaunchAuthenticationRequest()
    {
        Uri uri = DropboxOAuth2Helper.GetAuthorizeUri(_AppKey);

        Application.OpenURL(uri.AbsoluteUri);
    }
Esempio n. 19
0
        public void SetAccessToken(Uri result)
        {
            OAuth2Response result1 = DropboxOAuth2Helper.ParseTokenFragment(result);

            this.AccessToken = result1.AccessToken;
        }
Esempio n. 20
0
 /// <summary>
 /// Instantiates the authorization class and calculates the login URL
 /// </summary>
 internal DropboxAuthorization()
 {
     _Oauth2State = Guid.NewGuid().ToString("N");
     URI          = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, Configuration.DropboxAppKey, new Uri(Configuration.DropboxAuthorizationUrl), state: _Oauth2State);
 }
Esempio n. 21
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);
            }
        }
Esempio n. 22
0
 public async Task Initialize()
 {
     _state = Guid.NewGuid().ToString("N");
     this.AuthorizationUrl = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token,
                                                                 _isAccessRestricted ? DropboxHelper.DropboxAppFolderOnlyClientId : DropboxHelper.DropboxFullAccessClientId, RedirectionUrl, _state);
 }
Esempio n. 23
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                #region Dropbox

                if (AuthType == AuthenticateTypeList.Dropbox)
                {
                    this.Title          = "Dropbox Authentication";
                    this.db_Oauth2State = Guid.NewGuid().ToString("N");
                    var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, db_AppKey, new Uri(db_RedirectUri), state: db_Oauth2State);
                    this.webBrowser.Navigate(authorizeUri);
                }

                #endregion Dropbox

                #region Exact Online

                if (AuthType == AuthenticateTypeList.ExactOnline)
                {
                    this.Title       = "Exact Online Authentication";
                    eo_Authorization = new UserAuthorization();

                    try
                    {
                        UserAuthorizations.Authorize(eo_Authorization, eo_EndPoint, eo_ClientId, eo_ClientSecret, new Uri(eo_CallbackUrl));
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Invalid Exact Online's Client Secret!");
                        this.Result = false;
                        this.Close();
                        return;
                    }

                    eo_AccessToken = eo_Authorization.AccessToken;

                    if (eo_AccessToken == null)
                    {
                        this.Result = false;
                        this.Close();
                        return;
                    }
                    else
                    {
                        this.Result = true;

                        try
                        {
                            eo_Client = new ExactOnlineClient(eo_EndPoint, GetAccessToken);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Invalid Exact Online's End Point!");
                            this.Result = false;
                            this.Close();
                            return;
                        }

                        this.Close();
                        return;
                    }
                }

                #endregion Exact Online
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                this.Result = false;
                this.Close();
            }
        }
Esempio n. 24
0
 public static Uri GetAuthorizeUri(string state)
 {
     return(DropboxOAuth2Helper.GetAuthorizeUri(Api.appKey));
 }
Esempio n. 25
0
 public Uri GetAuthPageAddress()
 {
     return(DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, LocalKey.Dropbox_AppKey, "https://www.canself.com", state: Guid.NewGuid().ToString("N")));
 }