예제 #1
0
        /// <summary>
        /// Get a working provider (so, an access token) from Dropbox.
        /// </summary>
        /// <param name="savedState"></param>
        /// <param name="silent"></param>
        public async Task <string> Register(string savedState = null, bool silent = false)
        {
            var result = new TaskCompletionSource <string>();

            // Check if the saved token is still usable
            if (await ClientFactory(savedState))
            {
                result.SetResult(savedState);
                return(await result.Task);
            }

            // If the saved token was not usable and silent is true, return with failure
            if (silent)
            {
                result.SetResult(null);
                return(await result.Task);
            }

            // If it is not, try to get a new one
            var url = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Code,
                Obscure.CaesarDecode(Config.AppKey),
                (string)null);

            var form    = new CodeForm(url.ToString(), 43);
            var success = false;

            form.OnResult += async code =>
            {
                success = true;
                form.Close();

                var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
                    code,
                    Obscure.CaesarDecode(Config.AppKey),
                    Obscure.CaesarDecode(Config.AppSecret));

                if (response?.AccessToken != null && await ClientFactory(response.AccessToken))
                {
                    result.SetResult(response.AccessToken);
                }
                else
                {
                    result.SetResult(null);
                }
            };

            form.FormClosed += (sender, args) =>
            {
                if (!success)
                {
                    result.SetResult(null);
                }
            };

            Process.Start(url.ToString());
            form.Show();

            return(await result.Task);
        }
예제 #2
0
        public IActionResult DropboxAuth()
        {
            this.oauth2State = Guid.NewGuid().ToString("N");
            Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, appId, new Uri(RedirectUri), state: oauth2State);

            return(Redirect(authorizeUri.ToString()));
        }
예제 #3
0
        public Uri getAuthUri()
        {
            this.oauth2State = Guid.NewGuid().ToString("N");
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, App_key, new Uri(RedirectUri), oauth2State);

            return(authorizeUri);
        }
        public string SignIn(string sessionId)
        {
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, "bwhwa6n4oglbqu6",
                                                                   $"{Request.Scheme}://{Request.Host}/api/account/authorize", state: sessionId);

            return(authorizeUri.OriginalString);
        }
예제 #5
0
        public Uri GetAuthorizationUri()
        {
            oauth2State = Guid.NewGuid().ToString("N");
            var authRequestUrl = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, "unqwltt7mf1x5mh", RedirectUri, state: oauth2State);

            return(authRequestUrl);
        }
예제 #6
0
        async Task <string> GetToken()
        {
            var redirectUri = new Uri(REDIRECT_URI);

            var authorizeUrl = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, APP_KEY, new Uri(REDIRECT_URI));

            OpenBrowser(authorizeUrl.ToString());

            var http = new HttpListener();

            http.Prefixes.Add(REDIRECT_URI);
            http.Start();

            var context = await http.GetContextAsync();

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

            http.Stop();

            var code = Uri.UnescapeDataString(context.Request.QueryString["code"]);

            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, APP_KEY, APP_SECRET, REDIRECT_URI);

            return(response.AccessToken);
        }
        /// <summary>
        /// Authorizes an application to work with user data. Provides via a browser.
        /// </summary>
        /// <returns></returns>
        public async Task <string> Authorize()
        {
            var state   = Guid.NewGuid().ToString("N");
            var authUri = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Token,
                _appKey,
                _redirectUri,
                state: state);
            OAuth2Response result;

            using (var http = new HttpListener())
            {
                http.Prefixes.Add(_loopbackHost);
                http.Start();

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

                await HandleOAuth2Redirect(http).ConfigureAwait(false);

                // Handle redirect from JS and process OAuth response.
                result = await HandleJsRedirect(http).ConfigureAwait(false);
            }



            if (result.State != state)
            {
                // The state in the response doesn't match the state in the request.
                return(null);
            }

            return(result.AccessToken);
        }
예제 #8
0
        private static async Task <string> GetAccessToken(string key, string secret)
        {
            if (!string.IsNullOrEmpty(Settings.Default.USER_TOKEN))
            {
                return(Settings.Default.USER_TOKEN);
            }

            Console.WriteLine(
                "You'll need to authorize this account with PneumaticTube; a browser window will now open asking you to log into Dropbox and allow the app. When you've done that, you'll be given an access key. Enter the key here and hit Enter:");

            var oauth2State = Guid.NewGuid().ToString("N");

            // Pop open the authorization page in the default browser
            var url = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, key, (Uri)null, oauth2State);

            Process.Start(url.ToString());

            // Wait for the user to enter the key
            var token = Console.ReadLine();

            var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(token, key, secret);

            // Save the token
            Settings.Default.USER_TOKEN = response.AccessToken;
            Settings.Default.Save();

            return(response.AccessToken);
        }
예제 #9
0
        /// <summary>
        /// Gets the dropbox access token.
        /// <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 access token or null.</returns>
        private async Task <string> GetAccessToken()
        {
            Console.Write("Reset settings (Y/N) ");
            if (Console.ReadKey().Key == ConsoleKey.Y)
            {
                Settings.Default.Reset();
            }
            Console.WriteLine();

            var accessToken = Settings.Default.AccessToken;

            if (string.IsNullOrEmpty(accessToken))
            {
                try
                {
                    Console.WriteLine("Waiting for credentials.");
                    var state        = Guid.NewGuid().ToString("N");
                    var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ApiKey, RedirectUri, state: state);
                    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 result = await HandleJSRedirect(http);

                    if (result.State != state)
                    {
                        // The state in the response doesn't match the state in the request.
                        return(null);
                    }

                    Console.WriteLine("and back...");

                    // Bring console window to the front.
                    SetForegroundWindow(GetConsoleWindow());

                    accessToken = result.AccessToken;
                    var uid = result.Uid;
                    Console.WriteLine("Uid: {0}", uid);

                    Settings.Default.AccessToken = accessToken;
                    Settings.Default.Uid         = uid;

                    Settings.Default.Save();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                    return(null);
                }
            }

            return(accessToken);
        }
예제 #10
0
        public Uri StartAuthorisation()
        {
            string clientId = this.context.Settings.Dropbox_ClientId;

            // The user should go to this URI, login and get a code... and enter that into FinishAuthorisation
            return(DropboxOAuth2Helper.GetAuthorizeUri(clientId));
        }
        private void Start(string appKey)
        {
            this.oauth2State = Guid.NewGuid().ToString("N");
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, appKey, new Uri(RedirectUri), state: oauth2State);

            this.Browser.Navigate(authorizeUri);
        }
예제 #12
0
        public void OpenDefaultBrowserAndAskForAccess(string appKey)
        {
            //start code flow
            Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(appKey);

            Process.Start(authorizeUri.ToString());
        }
예제 #13
0
        /// <summary>
        ///     <para>Runs the Dropbox OAuth authorization process if not yet authenticated.</para>
        /// </summary>
        /// <returns></returns>
        public async Task Authorize()
        {
            if (string.IsNullOrWhiteSpace(AccessToken) == false)
            {
                IsAuthorized = true;
                // Already authorized
                return;
            }
            if (GetAccessTokenFromSettings())
            {
                IsAuthorized = true;
                // Found token and set AccessToken
                return;
            }
            // Run Dropbox authentication
            oauth2State = Guid.NewGuid().ToString("N");
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ClientId, new Uri(RedirectUri), oauth2State);
            var webView      = new WebView {
                Source = new UrlWebViewSource {
                    Url = authorizeUri.AbsoluteUri
                }
            };

            webView.Navigating += WebViewOnNavigating;
            var contentPage = new ContentPage {
                Content = webView
            };
            await Application.Current.MainPage.Navigation.PushModalAsync(contentPage);
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.oauth2State = Guid.NewGuid().ToString("N");
            Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, appKey, RedirectUri, state: oauth2State);

            this.Browser.Navigate(authorizeUri);
        }
예제 #15
0
        public IActionResult ConnectToDropbox()
        {
            var dropboxRedirect = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, dropboxAppKey, RedirectUri, tokenAccessType: TokenAccessType.Offline, scopeList: new[] { "files.content.write" });

            logger.LogInformation($"Getting user token from Dropbox: {dropboxRedirect} (redirect={RedirectUri})");
            return(Redirect(dropboxRedirect.ToString()));
        }
        /// <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()
        {
            Application.Current.Properties.Clear();

            if (string.IsNullOrWhiteSpace(this.AccessToken) == false)
            {
                // Already authorized
                this.OnAuthenticated?.Invoke();
                return;
            }

            // Run Dropbox authentication
            this.oauth2State = Guid.NewGuid().ToString("N");
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ClientId, new Uri(RedirectUri), this.oauth2State);
            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);
        }
예제 #17
0
        public DropboxTools()
        {
            try
            {
                // Variables
                DropboxClientConfig dropboxClientConfig;
                HttpClient          httpClient;
                Uri authURI;

                // Get authentication
                this.authState = Guid.NewGuid().ToString("N");
                authURI        = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, Global.AppKey, RedirectURI, state: this.authState);
                this.authURL   = authURI.AbsoluteUri.ToString();

                // Create dropbox client config
                dropboxClientConfig = new DropboxClientConfig(Global.AppName);

                // Create http client
                httpClient = new HttpClient
                {
                    Timeout = TimeSpan.FromMinutes(10)
                };

                // Create dropbox client
                dropboxClientConfig.HttpClient = httpClient;
                this.dropboxClient             = new DropboxClient(Global.AccessToken, dropboxClientConfig);
            }
            catch
            {
                // Error
            }
        }
예제 #18
0
        private async Task <string> GetTokenOnline()
        {
            var accessToken = string.Empty;

            try
            {
                var state        = Guid.NewGuid().ToString("N");
                var authorizeUri =
                    DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ApiKey, RedirectUri, state: state);
                var http = new HttpListener();
                http.Prefixes.Add(LoopbackHost);

                http.Start();

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

                await HandleOAuth2Redirect(http);

                var result = await HandleJSRedirect(http);

                if (result.State != state)
                {
                    return(null);
                }
                accessToken = result.AccessToken;
                SaveToken(accessToken);
            }
            catch (Exception e)
            {
                WorkspaceLogger.Log.Error(e);
                return(null);
            }

            return(accessToken);
        }
예제 #19
0
파일: Form1.cs 프로젝트: Nero-X/DropBoxAPI
 void GetAccessToken()
 {
     oauth2State = Guid.NewGuid().ToString("N");
     w.Show();
     w.Load(DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, "hzw1k2rtk9p5qcj", RedirectUri, state: oauth2State).ToString());
     w.LoadError += W_LoadError;
 }
        public void Start()
        {
            this.oauth2State = Guid.NewGuid().ToString("N");

            this.AuthorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Token, ApiConfig.DropboxClientId, new Uri(RedirectUri), state: this.oauth2State)
                                .ToString();
        }
예제 #21
0
        public ActionResult ConnectDropBox()
        {
            var settings    = _settingsService.GetSiteSettings();
            var oauth2State = Guid.NewGuid().ToString("N");
            var redirect    = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Code, settings.DropBoxSettings.ApplicationKey, "http://localhost:43729/Settings/Settings/DropboxCallback", oauth2State);

            return(Redirect(redirect.ToString()));
        }
예제 #22
0
        /// <summary>
        /// *** This Function is used to get DropBox Access Token URL
        /// </summary>
        /// <param name="dropBoxAppKey">The Dropbox Application Key</param>
        /// <param name="dropBoxAppSecret">The Dropbox Application Secret.</param>
        /// <param name="returnBackURL">The Dropbox Return Back URL.</param>
        /// <returns>Token URL.</returns>
        public static string getAccessTokenURL(string dropBoxAppKey, string dropBoxAppSecret, string returnBackURL)
        {
            var redirect = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Code,
                dropBoxAppKey,
                returnBackURL);

            return(redirect.ToString());
        }
예제 #23
0
 void SetupAuthorizeUri()
 {
     _oauth2State = Guid.NewGuid().ToString("N");
     if (!string.IsNullOrEmpty(AppKey))
     {
         var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, AppKey, new Uri(_redirectUri), _oauth2State);
         AuthUri = authorizeUri;
     }
 }
예제 #24
0
        public ActionResult Connect()
        {
            var redirect = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Code,
                appKey,
                RedirectUri,
                null);

            return(Redirect(redirect.ToString()));
        }
예제 #25
0
        private string CreateAuthUrl(string externalStateValue)
        {
            var url = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Code,
                dropboxAuthAppKey,
                RedirectURI,
                externalStateValue);

            return(url.ToString());
        }
예제 #26
0
        /// <summary>
        /// Startes the authorization process which will continue through an app
        /// activation.
        /// </summary>
        public static void AuthorizeAndContinue()
        {
            var authUri = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Token,
                App.AppKey,
                App.RedirectUri);

            WebAuthenticationBroker.AuthenticateAndContinue(
                authUri,
                App.RedirectUri);
        }
예제 #27
0
        private async Task LoginToDropbox()
        {
            oauth2State = Guid.NewGuid().ToString("N");
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, appKey, new Uri(RedirectUri), state: oauth2State);

            var result = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                authorizeUri,
                new Uri(RedirectUri));

            await ProcessResult(result);
        }
예제 #28
0
        public ActionResult Index()
        {
            var state = Guid.NewGuid().ToString("N");

            var redirect = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Code,
                appKey,
                RedirectUri,
                state);

            return(Redirect(redirect.ToString()));
        }
예제 #29
0
        // Task // Dropbox verbinden
        private async Task <string> DropboxConnect()
        {
            // Dropbox verbinden und Token erzeugen
            var authUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, "u2etrormxhi8v3i", new Uri("http://localhost:5000/admin/auth"));
            var result  = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, authUri, new Uri("http://localhost:5000/admin/auth"));

            // Resultat auswerten
            ProcessResult(result);

            // Rückgabe
            return(dropboxToken);
        }
예제 #30
0
        /// <summary>
        /// Runs the Dropbox OAuth authorization process.
        /// </summary>
        /// <returns>An asynchronous task.</returns>
        public static async Task Authorize()
        {
            var authUri = DropboxOAuth2Helper.GetAuthorizeUri(
                OAuthResponseType.Token,
                App.AppKey,
                App.RedirectUri);
            var result = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                authUri,
                App.RedirectUri);

            ProcessResult(result);
        }