Example #1
0
        private async void MainPage_AccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs args)
        {
            var deferral = args.GetDeferral();

            try
            {
                // MSA
                {
                    var provider = await GetProvider(MicrosoftProviderId, MsaAuthority);

                    var command = new AuthenticationCommand {
                        ClientId = MsaClientId, Scope = MsaClientId
                    };
                    WebAccountProviderCommand boundCommand = new WebAccountProviderCommand(provider, command.CommandInvoked);
                    args.WebAccountProviderCommands.Add(boundCommand);
                }

                // AAD
                // https://blogs.technet.microsoft.com/enterprisemobility/2015/08/03/develop-windows-universal-apps-with-azure-ad-and-the-windows-10-identity-api/
                {
                    var provider = await GetProvider(MicrosoftProviderId, MicrosoftProviderId + "/" /*AadAuthority*/);

                    var command = new AuthenticationCommand {
                        ClientId = AadClientId, Scope = string.Empty
                    };
                    var boundCommand = new WebAccountProviderCommand(provider, command.CommandInvoked);
                    args.WebAccountProviderCommands.Add(boundCommand);
                }
            }
            finally
            {
                deferral.Complete();
            }
        }
        private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
        {
            string token = string.Empty;

            // AccountClientID is ignored by MSA
            WebTokenRequest webTokenRequest = new WebTokenRequest(command.WebAccountProvider, AccountScopeRequested, AccountClientId);

            // If the user selected a specific account, RequestTokenAsync will return a token for that account.
            // The user may be prompted for credentials or to authorize using that account with your app
            // If the user selected a provider, the user will be prompted for credentials to login to a new account
            WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);

            // If a token was successfully returned, then store the WebAccount Id into local app data
            // This Id can be used to retrieve the account whenever needed. To later get a token with that account
            // First retrieve the account with FindAccountAsync, and include that webaccount
            // as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync
            if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
            {
                WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                userAccount = webTokenResponse.WebAccount;
                token       = webTokenResponse.Token;
            }

            // We succeeded in getting a valid user.
            if (userAccount != null)
            {
                // save user ID in local storage
                _settings.Values["userID"]    = userAccount.Id;
                _settings.Values["userEmail"] = userAccount.UserName;
            }

            AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested;

            OnAuthenticated?.Invoke(this, new AuthenticatedEventArgs(token));
        }
Example #3
0
        private async void GetMsaToken(WebAccountProviderCommand command)
        {
            WebTokenRequest       request = new WebTokenRequest(command.WebAccountProvider, "wl.basic");
            WebTokenRequestResult result  = await WebAuthenticationCoreManager.RequestTokenAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                WebAccount account = result.ResponseData[0].WebAccount;

                StoreWebAccount(account);



                //var restApi = new Uri(@"https://apis.live.net/v5.0/me?access_token=" + token);
                //var webAccount = await WebAuthenticationCoreManager.FindAccountAsync(command.WebAccountProvider, token);

                //using (var client = new HttpClient())
                //{
                //    var infoResult = await client.GetAsync(restApi);
                //    string content = await infoResult.Content.ReadAsStringAsync();

                //    var jsonObject = JsonObject.Parse(content);
                //    string id = jsonObject["id"].GetString();
                //    string username = jsonObject["name"].GetString();


                //    UserIdTextBlock.Text = id;
                //    UserNameTextBlock.Text = username;

                //    var asdf = new WebAccount(command.WebAccountProvider, username, WebAccountState.Connected);
            }
        }
 /// <summary>
 /// This event is generated when the user clicks on Account provider tile. This method is
 /// responsible for deciding what to do further.
 /// </summary>
 /// <param name="command">WebAccountProviderCommand instance that triggered the event.</param>
 private async void WebAccountProviderInvokedHandler(WebAccountProviderCommand command)
 {
     if (command.WebAccountProvider.Id.Equals(FACEBOOK_ID))
     {
         if (!isFacebookUserLoggedIn)
         {
             await AuthenticateToFacebookAsync();
         }
         else
         {
             OutputText("User is already logged in. If you support multiple accounts from the same provider then do something here to connect new user.");
         }
     }
     else if (command.WebAccountProvider.Id.Equals(TWITTER_ID))
     {
         if (!isTwitterUserLoggedIn)
         {
             await AuthenticateToTwitterAsync();
         }
         else
         {
             OutputText("User is already logged in. If you support multiple accounts from the same provider then do something here to connect new user.");
         }
     }
 }
        private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
        {
            // Show UI for signing in in the background in case of a slow connection and hide the sign in button
            LoadingHeader.Text       = "Signing in..";
            Loading_PR.IsActive      = true;
            GetStarted_sp.Visibility = Visibility.Collapsed;
            Loading_SP.Visibility    = Visibility.Visible;

            user = await MicrosoftAccount.SignIn(command.WebAccountProvider);

            if (user != null)
            {
                Loading_SP.Visibility    = Visibility.Collapsed;
                GetStarted_sp.Visibility = Visibility.Collapsed;
                OutputPanel.Visibility   = Visibility.Visible;
                ResultsText.Text         = "Hi " + user.AccountName + "!";
                ProfileImage.Fill        = user.Image;
                Loading_PR.IsActive      = false;
            }
            else
            {
                Loading_PR.IsActive      = false;
                Loading_SP.Visibility    = Visibility.Collapsed;
                GetStarted_sp.Visibility = Visibility.Visible;
            }
        }
Example #6
0
        private async void WebAccountProviderInvokedHandler(WebAccountProviderCommand command)
        {
            string externalLoginUri = command.WebAccountProvider.Id;
            ExternalLoginResult loginExternalResult = await ExternalLoginManager.GetExternalAccessTokenAsync(externalLoginUri);

            string accessToken = loginExternalResult.AccessToken;

            if (accessToken != null)
            {
                HttpResult result;
                using (AccountClient accountClient = ClientFactory.CreateAccountClient())
                {
                    result = await accountClient.AddExternalLoginAsync(new AddExternalLogin()
                    {
                        ExternalAccessToken = accessToken
                    });
                }
                if (result.Succeeded)
                {
                    AccountsSettingsPane.Show();
                }
                else
                {
                    await ErrorDialog.ShowErrorsAsync(result.Errors);
                }
            }
            else
            {
                await ErrorDialog.ShowErrorAsync("Failed to connect to external account.");
            }
        }
Example #7
0
        private void GetMsaToken(WebAccountProviderCommand command)
        {
            CurrentAccount = null;
            var task = GetMsaTokenAsync(command);

            signInStartedCallback(task);
        }
        /// <summary>
        /// Creates an AccountsSettingsPane with options for MSA or Facebook login.
        /// </summary>
        private static async void BuildSettingsPaneAsync(AccountsSettingsPane s,
                                                         AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            var deferral = e.GetDeferral();

            e.HeaderText = _paneMessage + "Get signed in to Lunch Scheduler.  " +
                           "You can use an existing Microsoft or Facebook account.";

            // Microsoft account
            var msa = new WebAccountProviderCommand(
                await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers"),
                MicrosoftAccountAuth);

            e.WebAccountProviderCommands.Add(msa);

            // Facebook
            // Built-in provider exists only on phone; if not availble, use WAB as a fallback
            var fbProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://facebook.com");

            var fb = new WebAccountProviderCommand(
                fbProvider ??
                new WebAccountProvider("LunchScheduler", "Facebook", new Uri(@"ms-appx:///Assets/FbIcon.png")),
                FacebookAuth);

            e.WebAccountProviderCommands.Add(fb);

            // Help commands
            e.Commands.Add(new SettingsCommand("help", "Get help signing in",
                                               async x => await Launcher.LaunchUriAsync(new Uri("http://bing.com"))));
            e.Commands.Add(new SettingsCommand("privacy", "Privacy policy",
                                               async x => await Launcher.LaunchUriAsync(new Uri("http://bing.com"))));

            deferral.Complete();
        }
        private async void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            AccountsSettingsPaneEventDeferral deferral = eventArgs.GetDeferral();

            HttpResult <ExternalLogin[]> result;

            using (AccountClient accountClient = ClientFactory.CreateAccountClient())
            {
                result = await accountClient.GetExternalLoginsAsync();
            }

            if (result.Succeeded)
            {
                eventArgs.HeaderText = "Please select a login provider.";
                WebAccountProviderCommandInvokedHandler providerCmdHandler = new WebAccountProviderCommandInvokedHandler(WebAccountProviderInvokedHandler);
                foreach (ExternalLogin externalLogin in result.Content)
                {
                    WebAccountProvider        provider        = new WebAccountProvider(externalLogin.Url, externalLogin.Name, App.LoginIcons[externalLogin.Name]);
                    WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, providerCmdHandler);
                    eventArgs.WebAccountProviderCommands.Add(providerCommand);
                }
            }
            else
            {
                await ErrorDialog.ShowErrorsAsync("Error connecting to external accounts.", result.Errors);
            }

            deferral.Complete();
        }
        private async void OnAccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            AccountsSettingsPaneEventDeferral deferral        = e.GetDeferral();
            WebAccountProviderCommand         providerCommand = new WebAccountProviderCommand(await MicrosoftAccount.GetProvider(), WebAccountProviderCommandInvoked);

            e.WebAccountProviderCommands.Add(providerCommand);
            deferral.Complete();
        }
        private async Task AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);

            WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);

            e.WebAccountProviderCommands.Add(providerCommand);
        }
        /// <summary>
        /// This event is generated when the user clicks on Accounts command in settings pane. During this event, add your
        /// WebAccountProviderCommand, WebAccountCommand, CredentialCommand and  SettingsCommand objects to make them available to the
        /// AccountsSettingsPane UI.
        /// </summary>
        /// <param name="accountsSettingsPane">Instance that triggered the event.</param>
        /// <param name="eventArgs">Event data describing the conditions that led to the event.</param>
        private void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            var deferral = eventArgs.GetDeferral();

            //Add header text.
            eventArgs.HeaderText = "This is sample text. You can put a message here to give context to user. This section is optional.";

            //Add WebAccountProviders
            WebAccountProviderCommandInvokedHandler providerCmdHandler = new WebAccountProviderCommandInvokedHandler(WebAccountProviderInvokedHandler);
            WebAccountProviderCommand facebookProviderCommand          = new WebAccountProviderCommand(facebookProvider, WebAccountProviderInvokedHandler);

            eventArgs.WebAccountProviderCommands.Add(facebookProviderCommand);
            WebAccountProviderCommand twitterProviderCommand = new WebAccountProviderCommand(twitterProvider, WebAccountProviderInvokedHandler);

            eventArgs.WebAccountProviderCommands.Add(twitterProviderCommand);

            //Add WebAccounts if available.
            WebAccountCommandInvokedHandler accountCmdHandler = new WebAccountCommandInvokedHandler(WebAccountInvokedHandler);

            if (isFacebookUserLoggedIn)
            {
                facebookAccount = new WebAccount(facebookProvider, facebookUserName, WebAccountState.Connected);
                WebAccountCommand facebookAccountCommand = new WebAccountCommand(
                    facebookAccount, WebAccountInvokedHandler,
                    SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage);
                eventArgs.WebAccountCommands.Add(facebookAccountCommand);
            }

            if (isTwitterUserLoggedIn)
            {
                twitterAccount = new WebAccount(twitterProvider, twitterUserName, WebAccountState.Connected);
                WebAccountCommand twitterAccountCommand = new WebAccountCommand(
                    twitterAccount, WebAccountInvokedHandler,
                    SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage);
                eventArgs.WebAccountCommands.Add(twitterAccountCommand);
            }

            // Add links if needed.
            Object commandID = 1;
            UICommandInvokedHandler globalLinkInvokedHandler = new UICommandInvokedHandler(GlobalLinkInvokedhandler);
            SettingsCommand         command = new SettingsCommand(
                commandID,
                "More details",
                globalLinkInvokedHandler);

            eventArgs.Commands.Add(command);

            SettingsCommand command1 = new SettingsCommand(
                commandID,
                "Privacy policy",
                globalLinkInvokedHandler);

            eventArgs.Commands.Add(command1);

            deferral.Complete();
        }
Example #13
0
        /// <summary>
        /// Initializes the AccountsSettingsPane with AAD login.
        /// </summary>
        private async void BuildAccountsPane(AccountsSettingsPane sender,
                                             AccountsSettingsPaneCommandsRequestedEventArgs args)
        {
            var deferral = args.GetDeferral();
            var command  = new WebAccountProviderCommand(await GetAadProviderAsync(), async(x) =>
                                                         await LoginAsync());

            args.WebAccountProviderCommands.Add(command);
            deferral.Complete();
        }
Example #14
0
        private async void GetMsaTokenAsync(WebAccountProviderCommand command)
        {
            WebTokenRequest       request = new WebTokenRequest(command.WebAccountProvider, "wl.basic");
            WebTokenRequestResult result  = await WebAuthenticationCoreManager.RequestTokenAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                string token = result.ResponseData[0].Token;
            }
        }
Example #15
0
        private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            // The order of providers displayed is determined by the order provided to the Accounts pane
            List <WebAccountProvider> providers = await GetAllProviders();

            foreach (WebAccountProvider provider in providers)
            {
                WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
                e.WebAccountProviderCommands.Add(providerCommand);
            }
        }
Example #16
0
        private async void OnAccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();

            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(ProviderId, Authority);

            WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);

            e.WebAccountProviderCommands.Add(providerCommand);

            deferral.Complete();
        }
Example #17
0
        private async void BuildPaneAsync(AccountsSettingsPane s,
                                          AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            var deferral    = e.GetDeferral();
            var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                "https://login.microsoft.com", "consumers");

            var command = new WebAccountProviderCommand(msaProvider, GetMsaTokenAsync);

            e.WebAccountProviderCommands.Add(command);
            deferral.Complete();
        }
Example #18
0
        private async void MainPage_AccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs args)
        {
            var d           = args.GetDeferral();
            var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                "https://login.microsoft.com",
                "consumers");

            var command = new WebAccountProviderCommand(msaProvider, GetMsaTokenAsync);

            args.WebAccountProviderCommands.Add(command);
            d.Complete();
        }
Example #19
0
        private async void GetMsaTokenAsync(WebAccountProviderCommand command)
        {
            var request = new WebTokenRequest(command.WebAccountProvider, "wl.basic");
            var result  = await WebAuthenticationCoreManager.RequestTokenAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                await DocumentManager.SetAccountAsync(result.ResponseData[0].WebAccount);

                await DocumentManager.LoadItemsAsync();
            }
        }
Example #20
0
        private async Task <WebTokenRequestResult> SignInAsync(string resource)
        {
            var taskCompletionSource = new TaskCompletionSource <WebTokenRequestResult>();

            TypedEventHandler <AccountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs> AccountCommandsRequestedHandler = null;

            AccountCommandsRequestedHandler = async(s, e) =>
            {
                Debug.WriteLine("AccountCommandsRequestedHandler");

                AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= AccountCommandsRequestedHandler;

                // In order to make async calls within this callback, the deferral object is needed
                AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
                if (deferral != null)
                {
                    // The Microsoft account provider is always present in Windows 10 devices, even IoT Core, as is the Azure AD plugin.
                    var providerCommand = new WebAccountProviderCommand(await GetProvider(), async(command) =>
                    {
                        Debug.WriteLine("WebAccountProviderCommandInvokedHandler");

                        try
                        {
                            WebTokenRequest wtr = new WebTokenRequest(command.WebAccountProvider, _scope, _clientId);
                            if (resource != null)
                            {
                                wtr.Properties.Add("resource", resource);
                            }

                            var wtrr = await RequestTokenWithTimeout(wtr);
                            SaveToken(wtrr, resource);

                            taskCompletionSource.SetResult(wtrr);
                        }
                        catch (Exception ex)
                        {
                            ServiceUtil.LogService.Write("Web Token Request Error: " + ex.Message, LoggingLevel.Error);
                            taskCompletionSource.SetResult(null);
                        }
                    });

                    e.WebAccountProviderCommands.Add(providerCommand);

                    deferral.Complete();
                }
            };

            AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += AccountCommandsRequestedHandler;
            await AccountsSettingsPane.ShowAddAccountAsync();

            return(await taskCompletionSource.Task);
        }
        private async Task AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            // FindAccountProviderAsync returns the WebAccountProvider of an installed plugin
            // The Provider and Authority specifies the specific plugin
            // This scenario only supports Microsoft accounts.

            // The Microsoft account provider is always present in Windows 10 devices, as is the Azure AD plugin.
            // If a non-installed plugin or incorect identity is specified, FindAccountProviderAsync will return null
            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);

            WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);

            e.WebAccountProviderCommands.Add(providerCommand);
        }
Example #22
0
        private async void OnAccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            // In order to make async calls within this callback, the deferral object is needed
            AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();

            try
            {
                foreach (var pi in _providers)
                {
                    // This scenario only lets the user have one account at a time.
                    // If there already is an account, we do not include a provider in the list
                    // This will prevent the add account button from showing up.
                    if (this.HasWebAccountInfo(pi.WebAccountType))
                    {
                        WebAccount account = await this.GetWebAccount(pi.WebAccountType);

                        if (account != null)
                        {
                            WebAccountCommand command = new WebAccountCommand(account, OnWebAccountRequested, pi.Actions);
                            e.WebAccountCommands.Add(command);
                        }
                    }
                    else
                    {
                        var provider = await this.GetProvider(pi.ProviderID, pi.Authority);

                        if (provider != null)
                        {
                            WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, OnWebAccountProviderRequested);
                            e.WebAccountProviderCommands.Add(providerCommand);
                        }
                    }
                }

                e.HeaderText = string.Format(Strings.Account.TextWebAccountManagerSignUpDescription, PlatformBase.CurrentCore.AppInfo.AppName);

                // You can add links such as privacy policy, help, general account settings
                e.Commands.Add(new SettingsCommand("privacypolicy", Strings.Resources.ViewTitlePrivacyPolicy, (c) => { PlatformBase.CurrentCore.NavigationBase.PrivacyPolicyCommand.Execute(null); this.Cleanup(); }));
                e.Commands.Add(new SettingsCommand("tos", Strings.Resources.ViewTitleTermsOfService, (c) => { PlatformBase.CurrentCore.NavigationBase.TermsOfServiceCommand.Execute(null); this.Cleanup(); }));
            }
            catch (Exception ex)
            {
                PlatformBase.CurrentCore.Logger.LogError(ex, "Failed to display the web account manager UI.");
                throw ex;
            }
            finally
            {
                deferral.Complete();
            }
        }
Example #23
0
        private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
        {
            if (command.WebAccountProvider.Id == "youtube")
            {
                // Show user registration/login for your app specific account type.
                // Store the user if registration/login successful
                var account = new WebAccount(command.WebAccountProvider, "App Specific User(" + DateTime.Now + ")", WebAccountState.Connected);
                var details = await App.YoutubeClient.AuthentificateAsync("578338675903-psaaj9eaukg7bvii3a4h17jd6r01vff2.apps.googleusercontent.com", "XcNuCRCoOcFXVoCzk2axCKhN");

                if (details != null)
                {
                    App.StoreNewAccountDataLocally(account, details);
                }
            }
        }
Example #24
0
        private async void BuildAccountsSettingsPaneAsync(AccountsSettingsPane s, AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            s.AccountCommandsRequested -= BuildAccountsSettingsPaneAsync;

            var deferral = e.GetDeferral();

            e.HeaderText = resourceService.GetString("SignInDescription");
            var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers");

            var command = new WebAccountProviderCommand(msaProvider, GetMsaToken);

            e.WebAccountProviderCommands.Add(command);

            deferral.Complete();
        }
        private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            List <WebAccountProvider> providers = new List <WebAccountProvider>();

            // Microsoft account and Azure AD providers will always return. Non-installed plugins or incorrect identities will return null
            providers.Add(await GetProvider(MicrosoftProviderId, MicrosoftAccountAuthority));
            providers.Add(await GetProvider(MicrosoftProviderId, AzureActiveDirectoryAuthority));
            providers.Add(await GetProvider(AppSpecificProviderId));

            foreach (WebAccountProvider provider in providers)
            {
                WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
                e.WebAccountProviderCommands.Add(providerCommand);
            }
        }
        /// <summary>
        /// This method customizes the accounts settings pane to setup user authentication with Microsoft accounts.
        /// You need to register this method to the AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested event.
        /// Don't forget to also remove the event handler (for example when user navigates away from your page).
        /// </summary>
        public async void BuildAccountPaneAsync(
            AccountsSettingsPane s,
            AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            var deferral = e.GetDeferral();

            var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                MicrosoftAccountProviderId,
                ConsumerAuthority);

            var command = new WebAccountProviderCommand(msaProvider, SignInUserAccountAsync);

            e.WebAccountProviderCommands.Add(command);

            deferral.Complete();
        }
Example #27
0
        private async void GetMsaTokenAsync(WebAccountProviderCommand command)
        {
            var request = new WebTokenRequest(command.WebAccountProvider, "wl.basic");
            var result  = await WebAuthenticationCoreManager.RequestTokenAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                await ProcessSuccessAsync(result);

                RaiseLoginComplete();
            }
            else
            {
                // If you receive an error when requesting a token, make sure you've associated your app with the Store as described in step one. Your app won't be able to get a token if you skipped this step.
                RaiseLoginFailed(result.ResponseStatus);
            }
        }
Example #28
0
        private async Task <UserAccount> GetMsaTokenAsync(WebAccountProviderCommand command)
        {
            var request = new WebTokenRequest(command.WebAccountProvider, tokenScope);
            var result  = await WebAuthenticationCoreManager.RequestTokenAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                UpdateWebAccount(result.ResponseData[0].WebAccount);
                CurrentAccount = await CreateUserAccount(result.ResponseData[0].Token);

                return(CurrentAccount);
            }
            else
            {
                throw new InvalidOperationException("WebAuthentication Response: " + result.ResponseStatus);
            }
        }
        public void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            var deferral = eventArgs.GetDeferral();

            ResourceLoader _res = ResourceLoader.GetForCurrentView();

            eventArgs.HeaderText = _res.GetString("LoginDescription");
            eventArgs.WebAccountProviderCommands.Clear();
            eventArgs.WebAccountCommands.Clear();

#if STEP2
            WebAccountProviderCommand googlePlusProviderCommand = new WebAccountProviderCommand(_app.SynchroManager.GetProvider(SynchroManager.ServerName.GooglePlus), WebAccountProviderInvokedHandler);
            eventArgs.WebAccountProviderCommands.Add(googlePlusProviderCommand);

            WebAccountProviderCommand facebookProviderCommand = new WebAccountProviderCommand(_app.SynchroManager.GetProvider(SynchroManager.ServerName.Facebook), WebAccountProviderInvokedHandler);
            eventArgs.WebAccountProviderCommands.Add(facebookProviderCommand);
#endif
            WebAccountProviderCommand dropboxProviderCommand = new WebAccountProviderCommand(_app.SynchroManager.GetProvider(SynchroManager.ServerName.Dropbox), WebAccountProviderInvokedHandler);
            eventArgs.WebAccountProviderCommands.Add(dropboxProviderCommand);

            WebAccountProviderCommand usbProviderCommand = new WebAccountProviderCommand(_app.SynchroManager.GetProvider(SynchroManager.ServerName.Usb), WebAccountProviderInvokedHandler);
            eventArgs.WebAccountProviderCommands.Add(usbProviderCommand);

#if STEP2
            if (_app.SynchroManager.LoggedIn(SynchroManager.ServerName.Facebook))
            {
                eventArgs.WebAccountCommands.Add(_app.SynchroManager.GetAccount(SynchroManager.ServerName.Facebook));
            }

            if (_app.SynchroManager.LoggedIn(SynchroManager.ServerName.GooglePlus))
            {
                eventArgs.WebAccountCommands.Add(_app.SynchroManager.GetAccount(SynchroManager.ServerName.GooglePlus));
            }
#endif
            if (_app.SynchroManager.LoggedIn(SynchroManager.ServerName.Dropbox))
            {
                eventArgs.WebAccountCommands.Add(_app.SynchroManager.GetAccount(SynchroManager.ServerName.Dropbox));
            }

            if (_app.SynchroManager.LoggedIn(SynchroManager.ServerName.Usb))
            {
                eventArgs.WebAccountCommands.Add(_app.SynchroManager.GetAccount(SynchroManager.ServerName.Usb));
            }

            deferral.Complete();
        }
 private void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
 {
     if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == MicrosoftAccountAuthority))
     {
         // ClientID is ignored by MSA
         AuthenticateWithRequestToken(command.WebAccountProvider, MicrosoftAccountScopeRequested, MicrosoftAccountClientId);
     }
     else if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == AzureActiveDirectoryAuthority))
     {
         AuthenticateWithRequestToken(command.WebAccountProvider, AzureActiveDirectoryAuthority, AzureActiveDirectoryClientId);
     }
     else if (command.WebAccountProvider.Id == AppSpecificProviderId)
     {
         // Show user registration/login for your app specific account type.
         // Store the user if registration/login successful
         StoreNewAccountDataLocally(new WebAccount(command.WebAccountProvider, "App Specific User", WebAccountState.None));
     }
 }
 private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
 {
     // ClientID is ignored by MSA
     await RequestTokenAndSaveAccount(command.WebAccountProvider, AccountScopeRequested, AccountClientId);
 }
        private async Task AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            // FindAccountProviderAsync returns the WebAccountProvider of an installed plugin
            // The Provider and Authority specifies the specific plugin
            // This scenario only supports Microsoft accounts.

            // The Microsoft account provider is always present in Windows 10 devices, as is the Azure AD plugin.
            // If a non-installed plugin or incorect identity is specified, FindAccountProviderAsync will return null   
            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);

            WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
            e.WebAccountProviderCommands.Add(providerCommand);
        }
        public async void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            AccountsSettingsPaneEventDeferral deferral = eventArgs.GetDeferral();

            HttpResult<ManageInfo> result;
            using (AccountClient accountClient = ClientFactory.CreateAccountClient())
            {
                result = await accountClient.GetManageInfoAsync();
            }

            if (!result.Succeeded)
            {
                await ErrorDialog.ShowErrorsAsync(result.Errors);
                // The log off command is not available on the account settings page if there are no accounts, so log off now
                LogOff();
                deferral.Complete();
                return;
            }

            ManageInfo manageInfo = result.Content;
            this.username = manageInfo.UserName;
            this.localProvider = manageInfo.LocalLoginProvider;

            eventArgs.HeaderText = "Manage your account logins";

            ////Add WebAccountProviders
            Dictionary<string, WebAccountProvider> webProviders = new Dictionary<string, WebAccountProvider>();
            WebAccountProviderCommandInvokedHandler providerCommandHandler = new WebAccountProviderCommandInvokedHandler(WebAccountProviderInvokedHandler);
            foreach (ExternalLogin externalLogin in manageInfo.ExternalLoginProviders)
            {
                WebAccountProvider provider = new WebAccountProvider(externalLogin.Url, externalLogin.Name, App.LoginIcons[externalLogin.Name]);
                WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, providerCommandHandler);
                eventArgs.WebAccountProviderCommands.Add(providerCommand);
                webProviders[provider.DisplayName] = provider;
            }

            WebAccountProvider localLoginProvider = new WebAccountProvider(manageInfo.LocalLoginProvider, manageInfo.LocalLoginProvider, null);
            webProviders[manageInfo.LocalLoginProvider] = localLoginProvider;

            ////Add WebAccounts and local accounts if available.
            bool hasLocalLogin = false;
            foreach (UserLoginInfo userLoginInfo in manageInfo.Logins)
            {
                WebAccountCommandInvokedHandler accountCommandHandler;
                SupportedWebAccountActions supportedActions = SupportedWebAccountActions.None;
                if (manageInfo.Logins.Length > 1)
                {
                    supportedActions |= SupportedWebAccountActions.Remove;
                }
                if (userLoginInfo.LoginProvider == manageInfo.LocalLoginProvider)
                {
                    hasLocalLogin = true;
                    supportedActions |= SupportedWebAccountActions.Manage;
                    accountCommandHandler = new WebAccountCommandInvokedHandler(LocalWebAccountInvokedHandler);
                }
                else
                {
                    accountCommandHandler = new WebAccountCommandInvokedHandler(WebAccountInvokedHandler);
                }
                WebAccount webAccount = new WebAccount(webProviders[userLoginInfo.LoginProvider], userLoginInfo.ProviderKey, WebAccountState.Connected);

                WebAccountCommand webAccountCommand = new WebAccountCommand(webAccount, accountCommandHandler, supportedActions);
                eventArgs.WebAccountCommands.Add(webAccountCommand);
            }

            if (!hasLocalLogin)
            {
                WebAccountProviderCommandInvokedHandler localProviderCmdHandler = new WebAccountProviderCommandInvokedHandler(LocalProviderInvokedHandler);
                WebAccountProviderCommand localProviderCommand = new WebAccountProviderCommand(localLoginProvider, localProviderCmdHandler);
                eventArgs.WebAccountProviderCommands.Add(localProviderCommand);
            }

            SettingsCommand logOffCommand = new SettingsCommand("Logoff", "Log off", new UICommandInvokedHandler(LogOffHandler));
            eventArgs.Commands.Add(logOffCommand);

            deferral.Complete();
        }
Example #34
0
        private async Task<UserAccount> GetMsaTokenAsync(WebAccountProviderCommand command)
        {
            var request = new WebTokenRequest(command.WebAccountProvider, tokenScope);
            var result = await WebAuthenticationCoreManager.RequestTokenAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                UpdateWebAccount(result.ResponseData[0].WebAccount);
                CurrentAccount = await CreateUserAccount(result.ResponseData[0].Token);
                return CurrentAccount;
            }
            else
            {
                throw new InvalidOperationException("WebAuthentication Response: " + result.ResponseStatus);
            }
        }
Example #35
0
        private async void OnWebAccountProviderRequested(WebAccountProviderCommand cmd)
        {
            // Retrieve the provider info instance for the requestd provider
            var pi = Platform.Current.WebAccountManager.GetProviderInfo(cmd.WebAccountProvider.Id);
            if (pi == null)
                throw new ArgumentNullException(nameof(pi));

            try
            {
                WebTokenRequest request = new WebTokenRequest(cmd.WebAccountProvider, pi.Scope, pi.ClientID);

                // Add any properties for this request from the provider info
                if (pi.RequestProperties != null)
                    foreach (var prop in pi.RequestProperties)
                        request.Properties.Add(prop);

                // If the user selected a specific account, RequestTokenAsync will return a token for that account.
                // The user may be prompted for credentials or to authorize using that account with your app
                // If the user selected a provider, the user will be prompted for credentials to login to a new account
                WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request);

                if (result.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    var webTokenResponse = result.ResponseData[0];
                    var webAccount = webTokenResponse.WebAccount;

                    // Wrapper the web account data
                    WebAccountInfo wi = new WebAccountInfo();
                    wi.Type = pi.WebAccountType;
                    wi.ProviderID = webAccount.WebAccountProvider.Id;
                    wi.AccountID = !string.IsNullOrEmpty(webAccount.Id) ? webAccount.Id : webAccount.UserName;
                    wi.Authority = webAccount.WebAccountProvider.Authority != null ? webAccount.WebAccountProvider.Authority : "";
                    wi.Token = webTokenResponse.Token;
                    this.SaveWebAccountInfo(wi);

                    Platform.Current.Logger.Log(LogLevels.Information, string.Format("Web Token request successful for AccountID: {0}", wi.AccountID));

                    // Success Callback
                    _successHandler(pi, wi, result);
                }
                else
                {
                    Platform.Current.Logger.Log(LogLevels.Information, "Web Token request error: " + result.ResponseStatus + " Code: " + result.ResponseError.ErrorMessage);

                    // Failed Callback
                    _failedHandler(pi, result);
                }

            }
            catch (Exception ex)
            {
                Platform.Current.Logger.LogError(ex, "Web Token request failed");
                _failedHandler(pi, null);
            }
            finally
            {
                this.Cleanup();
            }
        }
        private static async void OnAccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            // In order to make async calls within this callback, the deferral object is needed
            var deferral = e.GetDeferral();

            // The Microsoft account provider is always present in Windows 10 devices, as is the Azure AD plugin.
            // If a non-installed plugin or incorect identity is specified, FindAccountProviderAsync will return null   
            var webAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                AccountProviderId, Authority);

            var providerCommand = new WebAccountProviderCommand(webAccountProvider,
                async (c) =>
                {
                    try
                    {
                        currentToken = await GetTokenHelperAsync(c.WebAccountProvider, GraphResourceId);

                        DiscoveryClient discoveryClient = new DiscoveryClient(
                                async () => await GetTokenHelperAsync(null, DiscoveryResourceId));

                        //Get capabilities
                        capabilities = await discoveryClient.DiscoverCapabilitiesAsync() as Dictionary<string, CapabilityDiscoveryResult>;


                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        SignOutAsync().Wait();
                        tcs.TrySetResult(false);
                    }
                    var isValid = !String.IsNullOrEmpty(currentToken);

                    if (!isValid)
                        await SignOutAsync();

                    tcs.TrySetResult(isValid);
                });

            e.WebAccountProviderCommands.Add(providerCommand);

            deferral.Complete();
        }
        private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            // The order of providers displayed is determined by the order provided to the Accounts pane
            List<WebAccountProvider> providers = await GetAllProviders();

            foreach (WebAccountProvider provider in providers)
            {
                WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
                e.WebAccountProviderCommands.Add(providerCommand);
            }
        }
Example #38
0
        private async void BuildAccountsSettingsPaneAsync(AccountsSettingsPane s, AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            s.AccountCommandsRequested -= BuildAccountsSettingsPaneAsync;

            var deferral = e.GetDeferral();

            e.HeaderText = resourceService.GetString("SignInDescription");
            var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers");
            var command = new WebAccountProviderCommand(msaProvider, GetMsaToken);
            e.WebAccountProviderCommands.Add(command);

            deferral.Complete();
        }
        private async void WebAccountProviderInvokedHandler(WebAccountProviderCommand command)
        {
            string externalLoginUri = command.WebAccountProvider.Id;
            ExternalLoginResult loginExternalResult = await ExternalLoginManager.GetExternalAccessTokenAsync(externalLoginUri);
            if (loginExternalResult.AccessToken != null)
            {
                // Save the access token so we can check if the user has registered
                AppSettings settings = new AppSettings();
                settings.AccessToken = loginExternalResult.AccessToken;

                HttpResult<UserInfo> result;
                using (AccountClient accountClient = ClientFactory.CreateAccountClient())
                {
                    result = await accountClient.GetUserInfoAsync();
                }
                if (result.Succeeded)
                {
                    if (result.Content.HasRegistered)
                    {
                        accessTokenSource.TrySetResult(loginExternalResult.AccessToken);
                        this.Frame.GoBack();
                    }
                    else
                    {
                        RegisterExternalPageParameters parameters = new RegisterExternalPageParameters()
                        {
                            AccessTokenSource = accessTokenSource,
                            ExternalLoginUri = externalLoginUri,
                            UserInfo = result.Content
                        };
                        this.Frame.Navigate(typeof(RegisterExternalPage), parameters);
                    }
                }
                else
                {
                    await ErrorDialog.ShowErrorsAsync("Failed to connected to external account.", result.Errors);
                }
            }
            else
            {
                await ErrorDialog.ShowErrorAsync("Failed to connected to external account.");
            }
        }
Example #40
0
 private void GetMsaToken(WebAccountProviderCommand command)
 {
     CurrentAccount = null;
     var task = GetMsaTokenAsync(command);
     signInStartedCallback(task);
 }
        private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            List<WebAccountProvider> providers = new List<WebAccountProvider>();

            // Microsoft account and Azure AD providers will always return. Non-installed plugins or incorrect identities will return null
            providers.Add(await GetProvider(MicrosoftProviderId, MicrosoftAccountAuthority));
            providers.Add(await GetProvider(MicrosoftProviderId, AzureActiveDirectoryAuthority));
            providers.Add(await GetProvider(AppSpecificProviderId));

            foreach (WebAccountProvider provider in providers)
            {
                WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
                e.WebAccountProviderCommands.Add(providerCommand);
            }
        }
Example #42
0
        /// <summary>
        /// This event is generated when the user clicks on Accounts command in settings pane. During this event, add your
        /// WebAccountProviderCommand, WebAccountCommand, CredentialCommand and  SettingsCommand objects to make them available to the
        /// AccountsSettingsPane UI.
        /// </summary>
        /// <param name="accountsSettingsPane">Instance that triggered the event.</param>
        /// <param name="eventArgs">Event data describing the conditions that led to the event.</param>
        private void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            var deferral = eventArgs.GetDeferral();

            //Add header text.
            eventArgs.HeaderText = "This is sample text. You can put a message here to give context to user. This section is optional.";

            //Add WebAccountProviders
            WebAccountProviderCommandInvokedHandler providerCmdHandler = new WebAccountProviderCommandInvokedHandler(WebAccountProviderInvokedHandler);
            WebAccountProviderCommand facebookProviderCommand = new WebAccountProviderCommand(facebookProvider, WebAccountProviderInvokedHandler);
            eventArgs.WebAccountProviderCommands.Add(facebookProviderCommand);
            WebAccountProviderCommand twitterProviderCommand = new WebAccountProviderCommand(twitterProvider, WebAccountProviderInvokedHandler);
            eventArgs.WebAccountProviderCommands.Add(twitterProviderCommand);

            //Add WebAccounts if available.
            WebAccountCommandInvokedHandler accountCmdHandler = new WebAccountCommandInvokedHandler(WebAccountInvokedHandler);

            if (isFacebookUserLoggedIn)
            {
                facebookAccount = new WebAccount(facebookProvider, facebookUserName, WebAccountState.Connected);
                WebAccountCommand facebookAccountCommand = new WebAccountCommand(
                facebookAccount, WebAccountInvokedHandler,
                SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage);
                eventArgs.WebAccountCommands.Add(facebookAccountCommand);
            }

            if (isTwitterUserLoggedIn)
            {
                twitterAccount = new WebAccount(twitterProvider, twitterUserName, WebAccountState.Connected);
                WebAccountCommand twitterAccountCommand = new WebAccountCommand(
                twitterAccount, WebAccountInvokedHandler,
                SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage);
                eventArgs.WebAccountCommands.Add(twitterAccountCommand);
            }

            // Add links if needed.
            Object commandID = 1;
            UICommandInvokedHandler globalLinkInvokedHandler = new UICommandInvokedHandler(GlobalLinkInvokedhandler);
            SettingsCommand command = new SettingsCommand(
                commandID,
                "More details",
                globalLinkInvokedHandler);
            eventArgs.Commands.Add(command);

            SettingsCommand command1 = new SettingsCommand(
                commandID,
                "Privacy policy",
                globalLinkInvokedHandler);
            eventArgs.Commands.Add(command1);

            deferral.Complete();

        }
Example #43
0
 /// <summary>
 /// This event is generated when the user clicks on Account provider tile. This method is 
 /// responsible for deciding what to do further.
 /// </summary>
 /// <param name="command">WebAccountProviderCommand instance that triggered the event.</param>
 private async void WebAccountProviderInvokedHandler(WebAccountProviderCommand command)
 {
     if(command.WebAccountProvider.Id.Equals(FACEBOOK_ID))
     {
         if (!isFacebookUserLoggedIn)
         {
             await AuthenticateToFacebookAsync();
         }
         else
         {
             OutputText("User is already logged in. If you support multiple accounts from the same provider then do something here to connect new user.");
         }
     }
     else if (command.WebAccountProvider.Id.Equals(TWITTER_ID))
     {
         if (!isTwitterUserLoggedIn)
         {
             await AuthenticateToTwitterAsync();
         }
         else
         {
             OutputText("User is already logged in. If you support multiple accounts from the same provider then do something here to connect new user.");
         }
     }
 }
 private void LocalProviderInvokedHandler(WebAccountProviderCommand command)
 {
     SetPasswordFlyout setPasswordFlyout = new SetPasswordFlyout(username);
     setPasswordFlyout.Show();
 }
Example #45
0
        private async void OnAccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e)
        {
            // In order to make async calls within this callback, the deferral object is needed
            AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();

            try
            {
                foreach (var pi in _providers)
                {
                    // This scenario only lets the user have one account at a time.
                    // If there already is an account, we do not include a provider in the list
                    // This will prevent the add account button from showing up.
                    if (this.HasWebAccountInfo(pi.WebAccountType))
                    {
                        WebAccount account = await this.GetWebAccount(pi.WebAccountType);

                        if (account != null)
                        {
                            WebAccountCommand command = new WebAccountCommand(account, OnWebAccountRequested, pi.Actions);
                            e.WebAccountCommands.Add(command);
                        }
                    }
                    else
                    {
                        var provider = await this.GetProvider(pi.ProviderID, pi.Authority);
                        if (provider != null)
                        {
                            WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, OnWebAccountProviderRequested);
                            e.WebAccountProviderCommands.Add(providerCommand);
                        }
                    }
                }

                e.HeaderText = Strings.Account.TextWebAccountManagerSignUpDescription;

                // You can add links such as privacy policy, help, general account settings
                e.Commands.Add(new SettingsCommand("privacypolicy", Strings.Resources.ViewTitlePrivacyPolicy, (c) => { Platform.Current.Navigation.NavigateToPrivacyPolicyCommand.Execute(null); this.Cleanup(); }));
                e.Commands.Add(new SettingsCommand("tos", Strings.Resources.ViewTitleTermsOfService, (c) => { Platform.Current.Navigation.NavigateToTermsOfServiceCommand.Execute(null); this.Cleanup(); }));
            }
            catch(Exception ex)
            {
                Platform.Current.Logger.LogError(ex, "Failed to display the web account manager UI.");
                throw ex;
            }
            finally
            {
                deferral.Complete();
            }
        }
        private async void WebAccountProviderInvokedHandler(WebAccountProviderCommand command)
        {
            string externalLoginUri = command.WebAccountProvider.Id;
            ExternalLoginResult loginExternalResult = await ExternalLoginManager.GetExternalAccessTokenAsync(externalLoginUri);

            string accessToken = loginExternalResult.AccessToken;
            if (accessToken != null)
            {
                HttpResult result;
                using (AccountClient accountClient = ClientFactory.CreateAccountClient())
                {
                    result = await accountClient.AddExternalLoginAsync(new AddExternalLogin() { ExternalAccessToken = accessToken });
                }
                if (result.Succeeded)
                {
                    AccountsSettingsPane.Show();
                }
                else
                {
                    await ErrorDialog.ShowErrorsAsync(result.Errors);
                }
            }
            else
            {
                await ErrorDialog.ShowErrorAsync("Failed to connect to external account.");
            }
        }
        private async void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            AccountsSettingsPaneEventDeferral deferral = eventArgs.GetDeferral();

            HttpResult<ExternalLogin[]> result;
            using (AccountClient accountClient = ClientFactory.CreateAccountClient())
            {
                result = await accountClient.GetExternalLoginsAsync();
            }

            if (result.Succeeded)
            {
                eventArgs.HeaderText = "Please select a login provider.";
                WebAccountProviderCommandInvokedHandler providerCmdHandler = new WebAccountProviderCommandInvokedHandler(WebAccountProviderInvokedHandler);
                foreach (ExternalLogin externalLogin in result.Content)
                {
                    WebAccountProvider provider = new WebAccountProvider(externalLogin.Url, externalLogin.Name, App.LoginIcons[externalLogin.Name]);
                    WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, providerCmdHandler);
                    eventArgs.WebAccountProviderCommands.Add(providerCommand);
                }
            }
            else
            {
                await ErrorDialog.ShowErrorsAsync("Error connecting to external accounts.", result.Errors);
            }

            deferral.Complete();
        }
 private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
 {
     if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == MicrosoftAccountAuthority))
     {
         // ClientID is ignored by MSA
         await AuthenticateWithRequestToken(command.WebAccountProvider, MicrosoftAccountScopeRequested, MicrosoftAccountClientId);
     }
     else if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == AzureActiveDirectoryAuthority))
     {
         await AuthenticateWithRequestToken(command.WebAccountProvider, AzureActiveDirectoryScopeRequested, AzureActiveDirectoryClientId);
     }
     else if (command.WebAccountProvider.Id == AppSpecificProviderId)
     {
         // Show user registration/login for your app specific account type.
         // Store the user if registration/login successful
         StoreNewAccountDataLocally(new WebAccount(command.WebAccountProvider, "App Specific User(" + DateTime.Now + ")", WebAccountState.None));
     }
 }