public void GetMicrosoftAccountClient_NoSecret_InitializeDefaults()
        {
            var appId     = "appId";
            var returnUrl = "returnUrl";
            var scopes    = new string[] { "scope" };

            var client = OneDriveClient.GetMicrosoftAccountClient(
                appId,
                returnUrl,
                scopes) as OneDriveClient;

            Assert.IsNotNull(client.credentialCache, "Cache not initialized.");

            var initializedServiceInfoProvider = client.serviceInfoProvider as ServiceInfoProvider;

            Assert.IsNotNull(initializedServiceInfoProvider, "Service info provider not correctly initialized.");

            var initializedHttpProvider = client.HttpProvider as HttpProvider;

            Assert.IsNotNull(initializedHttpProvider, "HTTP provider not correctly initialized.");

            Assert.AreEqual(appId, client.appConfig.MicrosoftAccountAppId, "Incorrect app ID set.");
            Assert.IsNull(client.appConfig.MicrosoftAccountClientSecret, "Client secret set.");
            Assert.AreEqual(returnUrl, client.appConfig.MicrosoftAccountReturnUrl, "Incorrect return URL set.");
            Assert.AreEqual(scopes, client.appConfig.MicrosoftAccountScopes, "Incorrect scopes set.");
        }
        private async Task SignIn(ClientType clientType)
        {
            if (this.oneDriveClient == null)
            {
                this.oneDriveClient = clientType == ClientType.Consumer
                    ? OneDriveClient.GetMicrosoftAccountClient(
                    FormBrowser.MsaClientId,
                    FormBrowser.MsaReturnUrl,
                    FormBrowser.Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi())
                    : BusinessClientExtensions.GetClient(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId     = FormBrowser.AadClientId,
                    ActiveDirectoryReturnUrl = FormBrowser.AadReturnUrl,
                });
            }

            try
            {
                if (!this.oneDriveClient.IsAuthenticated)
                {
                    await this.oneDriveClient.AuthenticateAsync();
                }

                await LoadFolderFromPath();

                UpdateConnectedStateUx(true);
            }
            catch (OneDriveException exception)
            {
                // Swallow authentication cancelled exceptions, but reset the client
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        MessageBox.Show(
                            "Authentication failed",
                            "Authentication failed",
                            MessageBoxButtons.OK);

                        ((OneDriveClient)this.oneDriveClient).Dispose();
                        this.oneDriveClient = null;
                    }
                    else
                    {
                        PresentOneDriveException(exception);
                    }
                }
                else
                {
                    ((OneDriveClient)this.oneDriveClient).Dispose();
                    this.oneDriveClient = null;
                }
            }
        }
예제 #3
0
        /*
         * One Drive Initialization - Uses the Web Forms Authenticator
         */
        public async void initOneDriveAPI()
        {
            oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                onedrive_client_id,
                onedrive_redirect_uri,
                onedrive_scope,
                webAuthenticationUi: new FormsWebAuthenticationUi()
                );

            Console.WriteLine("OneDrive auth? " + oneDriveClient.IsAuthenticated);
        }
예제 #4
0
        private async void ExecuteSingIn()
        {
            if (this._OneDriveClient == null)
            {
                this._OneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                    ClientId,
                    ReturnUrl,
                    Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi());
            }

            try
            {
                if (!this._OneDriveClient.IsAuthenticated)
                {
                    await this._OneDriveClient.AuthenticateAsync();
                }

                if (this._OneDriveClient.IsAuthenticated)
                {
                    MessageBox.Show(
                        "Authentication was successful",
                        "Authentication was successful",
                        MessageBoxButton.OK);
                }
            }
            catch (OneDriveException exception)
            {
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        MessageBox.Show(
                            "Authentication failed",
                            "Authentication failed",
                            MessageBoxButton.OK);

                        var httpProvider = this._OneDriveClient.HttpProvider as HttpProvider;
                        if (httpProvider != null)
                        {
                            httpProvider.Dispose();
                        }

                        this._OneDriveClient = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        public async Task <IOneDriveClient> LoginAsync()
        {
            if (oneDriveClient == null)
            {
                oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                    OneDriveAuthenticationConstants.MSA_CLIENT_ID,
                    OneDriveAuthenticationConstants.RETURN_URL,
                    OneDriveAuthenticationConstants.Scopes,
                    OneDriveAuthenticationConstants.MSA_CLIENT_SECRET,
                    null, null,
                    new CustomServiceInfoProvider());
                try
                {
                    await oneDriveClient.AuthenticateAsync();
                }
                catch (Exception ex)
                {
                    Debug.Write(ex);
                }
            }

            try
            {
                if (!oneDriveClient.IsAuthenticated)
                {
                    await oneDriveClient.AuthenticateAsync();
                }

                return(oneDriveClient);
            }
            catch (OneDriveException exception)
            {
                // Swallow authentication cancelled exceptions
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        await dialogService.ShowMessage(
                            "Authentication failed",
                            "Authentication failed");
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            return(oneDriveClient);
        }
예제 #6
0
 /// <summary>
 /// Creates a OneDrive client for use against OneDrive consumer.
 /// </summary>
 /// <param name="appId">The application ID for Microsoft Account authentication.</param>
 /// <param name="returnUrl">The application return URL for Microsoft Account authentication.</param>
 /// <param name="scopes">The requested scopes for Microsoft Account authentication.</param>
 /// <param name="credentialCache">The cache instance for storing user credentials.</param>
 /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
 /// <param name="webAuthenticationUi">The <see cref="IWebAuthenticationUi"/> for displaying authentication UI to the user.</param>
 /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
 public static IOneDriveClient GetMicrosoftAccountClient(
     string appId,
     string returnUrl,
     string[] scopes,
     CredentialCache credentialCache          = null,
     IHttpProvider httpProvider               = null,
     IWebAuthenticationUi webAuthenticationUi = null)
 {
     return(OneDriveClient.GetMicrosoftAccountClient(
                appId,
                returnUrl,
                scopes,
                /* clientSecret */ null,
                credentialCache,
                httpProvider,
                new ServiceInfoProvider(webAuthenticationUi)));
 }
예제 #7
0
        public static async Task <IOneDriveClient> LoginAsync(string account, string code, string settingsPassPhrase)
        {
            if (string.IsNullOrEmpty(account))
            {
                throw new ArgumentNullException(nameof(account));
            }

            var refreshToken = LoadRefreshToken(account, settingsPassPhrase);

            IOneDriveClient client;

            if (!string.IsNullOrEmpty(refreshToken))
            {
                client = await OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(Secrets.CLIENT_ID, LIVE_LOGIN_DESKTOP_URI, scopes, Secrets.CLIENT_SECRET, refreshToken);
            }
            else
            {
                if (string.IsNullOrEmpty(code))
                {
                    client = await OneDriveClient.GetAuthenticatedMicrosoftAccountClient(Secrets.CLIENT_ID, LIVE_LOGIN_DESKTOP_URI, scopes, Secrets.CLIENT_SECRET, new WebAuthenticationUi(account));
                }
                else
                {
                    client = OneDriveClient.GetMicrosoftAccountClient(Secrets.CLIENT_ID, LIVE_LOGIN_DESKTOP_URI, scopes, Secrets.CLIENT_SECRET);
                    client.AuthenticationProvider.CurrentAccountSession = new AccountSession()
                    {
                        AccessToken = code
                    };
                }

                await client.AuthenticateAsync();

                if (!client.IsAuthenticated)
                {
                    throw new AuthenticationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.RetrieveAuthenticationCodeFromUri, LIVE_LOGIN_AUTHORIZE_URI));
                }
            }

            SaveRefreshToken(account, client.AuthenticationProvider.CurrentAccountSession.RefreshToken, settingsPassPhrase);

            return(client);
        }
예제 #8
0
        private async void signInToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.oneDriveClient == null)
            {
                this.oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                    FormBrowser.MsaClientId,
                    "https://login.live.com/oauth20_desktop.srf",
                    FormBrowser.Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi());
            }

            try
            {
                if (!this.oneDriveClient.IsAuthenticated)
                {
                    await this.oneDriveClient.AuthenticateAsync();
                }

                await LoadFolderFromPath();

                UpdateConnectedStateUx(true);
            }
            catch (OneDriveException exception)
            {
                // Swallow authentication cancelled exceptions
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        MessageBox.Show(
                            "Authentication failed",
                            "Authentication failed",
                            MessageBoxButtons.OK);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        public async Task <Item> GetItemsFromSelectionAsync(IOneDriveClient oneDriveClient = null)
        {
            const string msa_client_id = "0000000044128B55";
            var          offers        = new string[] { "onedrive.readwrite", "wl.signin" };

            if (oneDriveClient == null)
            {
                oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                    msa_client_id,
                    "https://login.live.com/oauth20_desktop.srf",
                    offers,
                    webAuthenticationUi: new FormsWebAuthenticationUi());

                await oneDriveClient.AuthenticateAsync();
            }

            var parts    = this.SelectionId.Split('.');
            var bundleID = parts[2];

            return
                (await
                 oneDriveClient.Drive.Items[bundleID].Request().Expand("thumbnails,children(expand=thumbnails)").GetAsync());
        }
예제 #10
0
        private async void ExecuteSingIn()
        {
            if (this._OneDriveClient == null)
            {
                this._OneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
                    ClientId,
                    ReturnUrl,
                    Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi());
            }

            try
            {
                if (!this._OneDriveClient.IsAuthenticated)
                {
                    await this._OneDriveClient.AuthenticateAsync();
                }

                if (this._OneDriveClient.IsAuthenticated)
                {
                    MessageBox.Show(
                        "Authentication was successful",
                        "Authentication was successful",
                        MessageBoxButton.OK);

                    // var expandValue =  ClientType.Consumer
                    //? "thumbnails,children($expand=thumbnails)"
                    //: "thumbnails,children";

                    var rootItem = await _OneDriveClient
                                   .Drive
                                   .Root
                                   .Request().Expand("thumbnails,children")
                                   .GetAsync();

                    foreach (var item in rootItem.Children.CurrentPage)
                    {
                        System.Console.WriteLine(item.Name);
                    }
                }
            }
            catch (OneDriveException exception)
            {
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        MessageBox.Show(
                            "Authentication failed",
                            "Authentication failed",
                            MessageBoxButton.OK);

                        var httpProvider = this._OneDriveClient.HttpProvider as HttpProvider;
                        if (httpProvider != null)
                        {
                            httpProvider.Dispose();
                        }

                        this._OneDriveClient = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
예제 #11
0
        private void Initialize()
        {
            if (Client != null)
            {
                return;
            }

            // Load credential cache
            CredentialCache credentialCache = new CredentialCache();

            if (!string.IsNullOrEmpty(Settings.Default.Credentials))
            {
                credentialCache.InitializeCacheFromBlob(Convert.FromBase64String(Settings.Default.Credentials));
            }

            // Authenticate with OneDrive
            Func <CredentialCache, AccountSession> authenticate = cc =>
            {
                Client = OneDriveClient.GetMicrosoftAccountClient(applicationId, applicationReturnUrl, applicationScopes, applicationSecret, cc, null, new OneDriveInfoProvider());
                Task <AccountSession> oneDriveSessionTask = Client.AuthenticateAsync();
                oneDriveSessionTask.Wait();
                return(oneDriveSessionTask.Result);
            };

            try
            {
                Session = authenticate(credentialCache);
            }
            catch
            {
                credentialCache = new CredentialCache();
                Session         = authenticate(credentialCache);
            }

            // Save credentials
            if (Session == null)
            {
                Settings.Default.Credentials = null;
                Settings.Default.Save();
            }
            else if (credentialCache.HasStateChanged)
            {
                Settings.Default.Credentials = Convert.ToBase64String(credentialCache.GetCacheBlob());
                Settings.Default.Save();
            }

            // Find specified root folder
            if (!Path.StartsWith("/") || !IsPathValid(Path))
            {
                throw new Exception("The specified path is not valid");
            }

            Task <Item> task;

            if (Path.Length == 1)
            {
                task = Client.Drive.Root.Request().GetAsync();
            }
            else
            {
                task = Client.Drive.Root.ItemWithPath(Path.Trim('/')).Request().GetAsync();
            }

            task.Wait();
            root = task.Result;
        }