public static async Task<string> GetAccessToken()
        {
            string token = null;

            //first try to get the token silently
            WebAccountProvider aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net");
            WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, String.Empty, clientId, WebTokenRequestPromptType.Default);
            webTokenRequest.Properties.Add("authority", "https://login.windows.net");
            webTokenRequest.Properties.Add("resource", ResourceUrl);
            WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
            //if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
            //{
            //    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
            //    userAccount = webTokenResponse.WebAccount;
            //    token = webTokenResponse.Token;
            //}
     //       else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
        //    {
                //get token through prompt
                webTokenRequest = new WebTokenRequest(aadAccountProvider, String.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
                webTokenRequest.Properties.Add("authority", "https://login.windows.net");
                webTokenRequest.Properties.Add("resource", ResourceUrl);
                webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    token = webTokenResponse.Token;
                    userAccount = webTokenResponse.WebAccount;
                }
         //   }
            if (userAccount != null)
            {
                // save user ID in local storage
                _settings.Values["userID"] = userAccount.Id;
                _settings.Values["userEmail"] = userAccount.UserName;
                _settings.Values["userName"] = userAccount.Properties["DisplayName"];              
            }
            return token;
        }    
        private async Task LogoffAndRemoveAccount(WebAccount account)
        {
            ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];

            if(account.WebAccountProvider.Id != AppSpecificProviderId)
            {
                await account.SignOutAsync();

                accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(account.Id);
                accountsContainer.Containers[AuthoritySubContainer].Values.Remove(account.Id);
            }
            else
            {
                //perform any actions needed to log off the app specific account
                accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(account.UserName);
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority);
            appSettings = ApplicationData.Current.RoamingSettings;
            WebTokenRequest wtr = new WebTokenRequest(wap, String.Empty, clientId);
            wtr.Properties.Add("resource", resource);

            var userID = appSettings.Values["userID"];
            if(userID != null)
            {
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(wap, (string)userID);
                if(userAccount != null)
                {
                    //Use saved account to get token
                    WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, userAccount);
                    if (wtrResult.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        userAccount = wtrResult.ResponseData[0].WebAccount;
                    }
                    else
                    {
                        MessageDialog messageDialog =
                            new MessageDialog("We tried to sign you in with the last account you used with this app," +
                                "but it didn't work out. Please sign in as a different user.");
                        await messageDialog.ShowAsync();
                        UpdateUXonSignOut();
                    }

                }
                else
                {
                    // the WebAccount Object is no longer available
                    wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString());
                    WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                    if (wtrResult.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        userAccount = wtrResult.ResponseData[0].WebAccount;
                    }

                }
               
            }
            else
            {
                //there is no recorded user so start sign-flow from start
                WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                if(wtrResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    userAccount = wtrResult.ResponseData[0].WebAccount;
                }
               
            }
            if(userAccount != null)
            {
                UpdateUXonSignIn();
            }
            else
            {
                //it totally failed
                UpdateUXonSignOut();
                MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
                await messageDialog.ShowAsync();
            }

        }
        public static async Task<string> TryAuthenticateSilentlyAsync()
        {
            try
            {

                var redir = GetAppRedirectURI();

                var aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                     AccountProviderId, Authority);

                // Check if there's a record of the last account used with the app.
                var userID = settings.Values["userID"];

                WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId);
                webTokenRequest.Properties.Add("resource", GraphResourceId);

                WebTokenRequestResult webTokenRequestResult;
                if (userID != null)
                {
                    // Get an account object for the user.
                    userAccount = await WebAuthenticationCoreManager.FindAccountAsync(
                        aadAccountProvider, (string)userID);

                    // Ensure that the saved account works for getting the token we need.
                    webTokenRequestResult =
                            await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount);
                }
                else
                {
                    webTokenRequestResult =
                            await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
                }


                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success
                    || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    currentToken = webTokenResponse.Token;

                    if (userAccount != null)
                    {
                        // Save user ID in local storage.
                        settings.Values["userID"] = userAccount.Id;
                        settings.Values["userEmail"] = userAccount.UserName;
                        settings.Values["userName"] = userAccount.Properties["DisplayName"];
                    }
                    return currentToken;

                }
                else 

                // Dont want to log during launch !!
                //if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
                //{
                //    webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
                //    webTokenRequest.Properties.Add("resource", GraphResourceId);

                //    //get token through prompt
                //    if (userID != null)
                //    {
                //        // Ensure that the saved account works for getting the token we need.
                //        webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount);
                //    }
                //    else
                //    {
                //        webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                //    }

                //    if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                //    {
                //        WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                //        userAccount = webTokenResponse.WebAccount;
                //        currentToken = webTokenResponse.Token;

                //        if (userAccount != null)
                //        {
                //            // Save user ID in local storage.
                //            settings.Values["userID"] = userAccount.Id;
                //            settings.Values["userEmail"] = userAccount.UserName;
                //            settings.Values["userName"] = userAccount.Properties["DisplayName"];
                //        }
                //        return true;
                //    }
                //    else
                //    {
                //        // The saved account could not be used for getting a token.
                //        // Make sure that the UX is ready for a new sign in.
                //        await SignOutAsync();
                //        return false;

                //    }
                //}
                {
                    // The saved account could not be used for getting a token.
                    // Make sure that the UX is ready for a new sign in.
                    await SignOutAsync();
                    return null;
                }
            }
            catch (Exception)
            {
                await SignOutAsync();
                return null;
            }


        }
        private async Task GetTokenSilent(WebAccountProvider Provider, WebAccount Account)
        {
            // Set the clientID and scope based on the authority. The authority tells us if the account is a Microsoft account or an Azure AD.
            String scope = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountScopeRequested : AzureActiveDirectoryScopeRequested;
            String clientID = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountClientId : AzureActiveDirectoryClientId;

            WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, scope, clientID);

            // Azure Active Directory requires a resource to return a token
            if (Provider.Authority == "organizations")
            {
                webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
            }

            WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, Account);

            if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
            {
                rootPage.NotifyUser("Silent request successful for user:"******"Cannot retrieve token silently because user interaction is required to complete this request.", NotifyType.ErrorMessage);
            }
            else
            {
                rootPage.NotifyUser("Web Token request error: " + webTokenRequestResult.ResponseStatus + " Code: " + webTokenRequestResult.ResponseError.ErrorMessage, NotifyType.StatusMessage);
            }
        }
        private void Button_Reset_Click(object sender, RoutedEventArgs e)
        {
            defaultAccount = null;
            defaultProvider = null;
            button_GetTokenSilently.IsEnabled = false;
            textblock_SignedInStatus.Text = "Not signed in";
            textblock_SignedInStatus.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
            listview_SignedInAccounts.Items.Clear();

        }
Esempio n. 7
0
        private async Task<WebAccount> GetWebAccount()
        {
            if (webAccount != null)
            {
                return webAccount;
            }

            string providerId = ApplicationData.Current.LocalSettings.Values["CurrentUserProviderId"]?.ToString();
            string accountId = ApplicationData.Current.LocalSettings.Values["CurrentUserId"]?.ToString();

            if (null == providerId || null == accountId)
            {
                return null;
            }

            var provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(providerId);
            webAccount = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountId);
            return webAccount;
        }
        private async Task<WebAccount> GetWebAccount()
        {
            String accountID = ApplicationData.Current.LocalSettings.Values[StoredAccountIdKey] as String;
            String providerID = ApplicationData.Current.LocalSettings.Values[StoredProviderIdKey] as String;
            String authority = ApplicationData.Current.LocalSettings.Values[StoredAuthorityKey] as String;

            WebAccount account;

            WebAccountProvider provider = await GetProvider(providerID);

            if (providerID == AppSpecificProviderId)
            {
                account = new WebAccount(provider, accountID, WebAccountState.None);
            }
            else
            {
                account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID);

                // The account has been deleted if FindAccountAsync returns null
                if (account == null)
                {
                    RemoveAccountData();
                }
            }

            return account;
        }
        // Get an access token for the given context and resourceId. An attempt is first made to 
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        public static async Task<string> GetTokenHelperAsync()
        {

            string token = null;

            aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority);

            // Check if there's a record of the last account used with the app.
            var userID = _settings.Values["userID"];

            if (userID != null)
            {

                WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId);
                webTokenRequest.Properties.Add("resource", ResourceUrl);

                // Get an account object for the user.
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(aadAccountProvider, (string)userID);


                // Ensure that the saved account works for getting the token we need.
                WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount);
                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    token = webTokenResponse.Token;

                }
                else
                {
                    // The saved account could not be used for getting a token.
                    // Make sure that the UX is ready for a new sign in.
                    SignOut();
                }

            }
            else
            {
                // There is no recorded user. Start a sign-in flow without imposing a specific account.

                WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
                webTokenRequest.Properties.Add("resource", ResourceUrl);

                WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                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;
                _settings.Values["userName"] = userAccount.Properties["DisplayName"];

                return token;
            }

            // We didn't succeed in getting a valid user. Clear the app settings so that another user can sign in.
            else
            {

                SignOut();
                return null;
            }


        }
Esempio n. 10
0
        public async Task <MsalTokenResponse> AcquireTokenSilentAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenSilentParameters acquireTokenSilentParameters)
        {
            using (_logger.LogMethodDuration())
            {
                // Important: MSAL will have already resolved the authority by now,
                // so we are not expecting "common" or "organizations" but a tenanted authority
                bool isMsa = await IsMsaRequestAsync(
                    authenticationRequestParameters.Authority,
                    null,
                    _wamOptions.MsaPassthrough)
                             .ConfigureAwait(false);

                IWamPlugin wamPlugin = isMsa ? _msaPlugin : _aadPlugin;

                WebAccountProvider provider;
                if (_wamOptions.MsaPassthrough)
                {
                    provider = await GetProviderAsync(
                        "organizations", false).ConfigureAwait(false);
                }
                else
                {
                    provider = await GetProviderAsync(
                        authenticationRequestParameters.AuthorityInfo.CanonicalAuthority,
                        isMsa).ConfigureAwait(false);
                }

                WebAccount webAccount = await FindWamAccountForMsalAccountAsync(
                    provider,
                    wamPlugin,
                    authenticationRequestParameters.Account,
                    null, // ATS requires an account object, login_hint is not supported on its own
                    authenticationRequestParameters.AppConfig.ClientId).ConfigureAwait(false);

                if (webAccount == null && _wamOptions.MsaPassthrough)
                {
                    return(await AcquireMsaTokenSilentForPassthroughAsync(
                               authenticationRequestParameters,
                               provider).ConfigureAwait(false));
                }

                if (webAccount == null)
                {
                    throw new MsalUiRequiredException(
                              MsalError.InteractionRequired,
                              "Could not find a WAM account for the silent request.");
                }

                WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                    provider,
                    authenticationRequestParameters,
                    isForceLoginPrompt : false,
                    isAccountInWam : true,
                    isInteractive : false)
                                                  .ConfigureAwait(false);

                // For MSA-PT scenario, MSAL's authority is wrong. MSAL will use Account.HomeTenantId
                // which will essentialyl be /consumers. This is wrong, we are not trying to obtain
                // an MSA token, we are trying to obtain an ADD *guest* token.
                string differentAuthority = null;
                if (_wamOptions.MsaPassthrough &&
                    authenticationRequestParameters.Authority is AadAuthority aadAuthority &&
                    aadAuthority.IsConsumers())
                {
                    differentAuthority = authenticationRequestParameters.Authority.GetTenantedAuthority("organizations", forceTenantless: true);
                }

                WamAdapters.AddMsalParamsToRequest(authenticationRequestParameters, webTokenRequest, _logger, differentAuthority);

                var wamResult =
                    await _wamProxy.GetTokenSilentlyAsync(webAccount, webTokenRequest).ConfigureAwait(false);

                return(WamAdapters.CreateMsalResponseFromWamResponse(
                           wamResult,
                           wamPlugin,
                           authenticationRequestParameters.AppConfig.ClientId,
                           _logger,
                           isInteractive: false));
            }
        }
        async public void acquireTokenAsync(
            string authority,
            bool validateAuthority,
            string resourceUrl,
            string clientId,
            string redirectUrl,
            string userId,
            string extraQueryParams,
            IPromise promise)
        {
            WebAccountProvider authContext;

            try
            {
                authContext = await getOrCreateContext(authority);
            }
            catch (Exception ex)
            {
                promise.Reject(ex);
                return;
            }


            RunOnDispatcher(async() =>
            {
                try
                {
                    WebAccount account  = await TryGetUserAccount(authContext);
                    WebTokenRequest wtr = new WebTokenRequest(authContext, "", clientId, WebTokenRequestPromptType.Default);
                    wtr.Properties.Add("resource", resourceUrl);
                    WebTokenRequestResult wtrr;
                    if (account != null)
                    {
                        wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, account);
                    }
                    else
                    {
                        wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                    }

                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        WebTokenResponse response = wtrr.ResponseData[0];
                        account = wtrr.ResponseData[0].WebAccount;
                        if (!string.IsNullOrEmpty(account?.Id))
                        {
                            // store the user's account id so it can be used in successive requests
                            Windows.Storage.ApplicationData.Current.LocalSettings.Values["CurrentUserId"] = account.Id;
                        }
                        var props = new Dictionary <string, string>(response.Properties);

                        AuthenticationResult result = new AuthenticationResult(response.Token, props);

                        promise.Resolve(result);
                    }
                    else
                    {
                        promise.Reject($"{wtrr.ResponseError.ErrorCode}", new Exception(wtrr.ResponseError.ErrorMessage));
                    }
                }
                catch (Exception ex)
                {
                    promise.Reject(ex);
                    return;
                }
            });
        }
Esempio n. 12
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority);

            appSettings = ApplicationData.Current.RoamingSettings;
            WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId);

            wtr.Properties.Add("resource", resource);

            // Check if there's a record of the last account used with the app
            var userID = appSettings.Values["userID"];

            if (userID != null)
            {
                // Get an account object for the user
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(wap, (string)userID);

                if (userAccount != null)
                {
                    // Ensure that the saved account works for getting the token we need
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, userAccount);

                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        userAccount = wtrr.ResponseData[0].WebAccount;
                    }
                    else
                    {
                        // The saved account could not be used for getitng a token
                        MessageDialog messageDialog = new MessageDialog("We tried to sign you in with the last account you used with this app, but it didn't work out. Please sign in as a different user.");
                        await messageDialog.ShowAsync();

                        // Make sure that the UX is ready for a new sign in
                        UpdateUXonSignOut();
                    }
                }
                else
                {
                    // The WebAccount object is no longer available. Let's attempt a sign in with the saved username
                    wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString());
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);

                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        userAccount = wtrr.ResponseData[0].WebAccount;
                    }
                }
            }
            else
            {
                // There is no recorded user. Let's start a sign in flow without imposing a specific account.
                WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);

                if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    userAccount = wtrr.ResponseData[0].WebAccount;
                }
            }

            if (userAccount != null) // we succeeded in obtaining a valid user
            {
                // save user ID in local storage
                UpdateUXonSignIn();
            }
            else
            {
                // nothing we tried worked. Ensure that the UX reflects that there is no user currently signed in.
                UpdateUXonSignOut();
                MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
                await messageDialog.ShowAsync();
            }
        }
 protected void GetLoggedInUserInfo()
 {
     activeUser       = (User)Session["ActiveUser"];
     activeWebAccount = (WebAccount)Session["ActiveWebAccount"];
 }
Esempio n. 14
0
        public async Task <string> TryFetchTransferTokenSilentAsync(AuthenticationRequestParameters authenticationRequestParameters, WebAccount account)
        {
            _logger.Verbose("WAM MSA-PT - fetching transfer token for silent flow");

            var webTokenRequestMsa = await _msaPlugin.CreateWebTokenRequestAsync(
                account.WebAccountProvider,
                authenticationRequestParameters,
                isForceLoginPrompt : false,
                isInteractive : false,
                isAccountInWam : true,
                TransferTokenScopes)
                                     .ConfigureAwait(false);

            WamAdapters.AddMsalParamsToRequest(authenticationRequestParameters, webTokenRequestMsa, _logger);

            var transferResponse = await _wamProxy.RequestTokenForWindowAsync(
                _parentHandle,
                webTokenRequestMsa,
                account)
                                   .ConfigureAwait(true);

            return(ExtractTransferToken(
                       authenticationRequestParameters.AppConfig.ClientId,
                       transferResponse,
                       isInteractive: false));
        }
Esempio n. 15
0
        // Get an access token for the given context and resourceId. An attempt is first made to
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        private async Task BeginGetAuthTokenAsync()
        {
            string token = null;

            // 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
            accountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, consumerAuthority);

            // Check if there's a record of the last account used with the app
            var userID = _settings.Values["userID"];

            if (userID != null)
            {
                WebTokenRequest webTokenRequest = new WebTokenRequest(accountProvider, AccountScopeRequested, AccountClientId);

                // Get an account object for the user
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(accountProvider, (string)userID);


                // Ensure that the saved account works for getting the token we need
                //WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount);
                WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount);

                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    token       = webTokenResponse.Token;
                }
                else
                {
                    // The saved account could not be used for getting a token
                    // Make sure that the UX is ready for a new sign in
                    SignOut();
                }
            }
            else
            {
                // There is no recorded user.
                // Check if a default MSA account has been set already.
                accountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId);

                // Check if the returned authority is "consumers"
                if (accountProvider?.Authority == consumerAuthority)
                {
                    // If it is, then there’s a default MSA account present and there’s no need to show account control
                    WebTokenRequest webTokenRequest = new WebTokenRequest(accountProvider, AccountScopeRequested, AccountClientId);

                    // This is where most of the magic happens.The provider you specified takes over, trying to use the currently
                    // signed in user(or any account saved on the system) to obtain the token you requested without prompting the user.
                    //WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                    WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);

                    if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                        userAccount = webTokenResponse.WebAccount;
                        token       = webTokenResponse.Token;
                    }
                }
                else
                {
                    // There is no default account or the returned authority is not "consumer", so we must show account control
                    // The AccountCommandsRequested event triggers before the Accounts settings pane is displayed
                    AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested;
                    AccountsSettingsPane.Show();
                    return;
                }
            }

            // 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;

                OnAuthenticated?.Invoke(this, new AuthenticatedEventArgs(token));
            }

            // We didn't succeed in getting a valid user. Clear the app settings so that another user can sign in.
            else
            {
                SignOut();
                OnAuthenticated?.Invoke(this, new AuthenticatedEventArgs(string.Empty));
            }
        }
Esempio n. 16
0
        void InitializeWebAccounts()
        {
            //Initialize facebok account object if user was already logged in.
            Object facebookToken = roamingSettings.Values[FACEBOOK_OAUTH_TOKEN];
            if (facebookToken == null)
            {
                isFacebookUserLoggedIn = false;
            }
            else
            {
                Object facebookUser = roamingSettings.Values[FACEBOOK_USER_NAME];
                if (facebookUser != null)
                {
                    facebookUserName = facebookUser.ToString();
                    facebookAccount = new WebAccount(facebookProvider, facebookUserName, WebAccountState.Connected);
                    isFacebookUserLoggedIn = true;
                }
            }

            //Initialize twitter account if user was already logged in.
            Object twitterToken = roamingSettings.Values[TWITTER_OAUTH_TOKEN];
            Object twitterTokenSecret = roamingSettings.Values[TWITTER_OAUTH_TOKEN_SECRET];
            if (twitterToken == null || twitterTokenSecret == null)
            {
                isTwitterUserLoggedIn = false;
            }
            else
            {
                Object twitteruser = roamingSettings.Values[TWITTER_USER_NAME];
                if (twitteruser != null)
                {
                    twitterUserName = twitteruser.ToString();
                    twitterAccount = new WebAccount(twitterProvider, twitterUserName, WebAccountState.Connected);
                    isTwitterUserLoggedIn = true;
                }
            }
        }
Esempio n. 17
0
        public static IAsyncInfo RequestTokenWithWebAccountForWindowAsync(IntPtr appWindow, WebTokenRequest request, WebAccount webAccount)
        {
            var iid = GuidGenerator.CreateIID(typeof(IAsyncOperation <WebTokenRequestResult>));

            return((IAsyncInfo)webAuthenticationCoreManagerInterop.RequestTokenWithWebAccountForWindowAsync(appWindow, request, webAccount, iid));
        }
Esempio n. 18
0
        /// *************************************************************************************************
        /// <summary>
        ///     09/22/2015 16:39 version
        ///     Website-Account Xml document is mapped to Object, then passed to WebServices as a JSON string.
        /// </summary>
        /// <param name="doc">Imported file content read as an XmlDocument</param>
        /// <param name="fName">File name (excluding path section)</param>
        /// <returns>Process status true if procees was completed ok, else false</returns>
        /// -------------------------------------------------------------------------------------------------
        bool IXmlFiles.ProcessWebsiteAccountFiles(XmlDocument doc, string fName, EtlTimer syncRow)
        {
            ServiceResponse rStatus = new ServiceResponse();
            //WebServiceManager wsm = new WebServiceManager();
            ///  ----------------------------------------------------------------------
            //  Account section
            ///  ----------------------------------------------------------------------            ///
            XmlNode    account = doc.DocumentElement.SelectSingleNode("/account");
            WebAccount ord     = new WebAccount();

            ord.OrderType = "nbi";
            ord.AccountId = dat.AttributeValidation_String(account, "accountid", 20);                   //  20
            ///  ----------------------------------------------------------------------
            //  Locale Section
            ///  ----------------------------------------------------------------------
            XmlNode locale = doc.DocumentElement.SelectSingleNode("/account/locale");

            ord.Language = dat.AttributeValidation_String(locale, "lang", 5);                           //  5
            ord.SiteUsed = dat.AttributeValidation_String(locale, "siteused", 10);                      //  10
            ord.Currency = dat.AttributeValidation_String(locale, "currency", 10);                      //  10
            ///  ----------------------------------------------------------------------
            //  Contact (account) section
            ///  ----------------------------------------------------------------------
            XmlNode contact = doc.DocumentElement.SelectSingleNode("/account/contact");

            ord.Email       = dat.SingleNodeValidation_Text(contact, "email", 60);                      //  60
            ord.Title       = dat.SingleNodeValidation_Text(contact, "title", 20);                      //  20
            ord.Forename    = dat.SingleNodeValidation_Text(contact, "forename", 70);                   //  70
            ord.Surname     = dat.SingleNodeValidation_Text(contact, "surname", 70);                    //  70
            ord.CompanyName = dat.SingleNodeValidation_Text(contact, "company", 300);                   //  300
            ord.Industry    = dat.SingleNodeValidation_Text(contact, "industry", 200);                  //  200
            ord.Telephone   = dat.SingleNodeValidation_Text(contact, "telephone", 30);                  //  30
            ///  ----------------------------------------------------------------------
            //  Address Section Process - (Cardholder)
            ///  ----------------------------------------------------------------------
            XmlNode cardHolder = doc.DocumentElement.SelectSingleNode("/account/address[@type='cardholder']");

            ord.AddressCardHolderTown     = dat.SingleNodeValidation_Text(cardHolder, "town", 150);      //  150
            ord.AddressCardHolderCounty   = dat.SingleNodeValidation_Text(cardHolder, "county", 150);    //  150
            ord.AddressCardHolderPostCode = dat.SingleNodeValidation_Text(cardHolder, "postcode", 30);   //  30
            ord.AddressCardHolderCountry  = dat.SingleNodeValidation_Text(cardHolder, "country", 200);   //  200
            //  Line section within Cardholder address section
            XmlNodeList xLt = cardHolder.SelectNodes("/account/address[@type='cardholder']/line");

            foreach (XmlNode xc in xLt)
            {
                int index = dat.AttributeValidation_Int(xc, "index");
                switch (index)
                {
                case 1:
                    ord.AddressCardHolderLine1 = xc.InnerText;              //  300
                    if (ord.AddressCardHolderLine1.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine1.Substring(0, 300);
                        ord.AddressCardHolderLine1 = txt;
                    }
                    break;

                case 2:
                    ord.AddressCardHolderLine2 = xc.InnerText;              //  300
                    if (ord.AddressCardHolderLine2.Length > 300)
                    {
                        string txt = ord.AddressCardHolderLine2.Substring(0, 300);
                        ord.AddressCardHolderLine2 = txt;
                    }
                    break;

                default:
                    break;
                }
            }
            ///  ----------------------------------------------------------------------
            //  Address Section - (Delivery)
            ///  ----------------------------------------------------------------------
            XmlNodeList delivery = doc.DocumentElement.SelectNodes("/account/address[@type='delivery']");

            foreach (XmlNode del in delivery)
            {
                /// Contact information within delivery address
                XmlNode delLine = del.SelectSingleNode("/account/address[@type='delivery']/contact");
                ord.AddressDeliveryForename  = dat.SingleNodeValidation_Text(delLine, "forename", 70);      //  70
                ord.AddressDeliverySurname   = dat.SingleNodeValidation_Text(delLine, "surname", 70);       //  70
                ord.AddressDeliveryTelephone = dat.SingleNodeValidation_Text(delLine, "telephone", 30);     //  70
                ///
                ord.AddressDeliveryCompany = dat.SingleNodeValidation_Text(del, "company", 300);            //  300
                /// Line section within Delivery address section
                XmlNodeList xnLine = del.SelectNodes("/account/address[@type='delivery']/line");
                foreach (XmlNode xd in xnLine)
                {
                    int index = dat.AttributeValidation_Int(xd, "index");
                    switch (index)
                    {
                    case 1:
                        ord.AddressDeliveryLine1 = xd.InnerText;                //  300
                        if (ord.AddressDeliveryLine1.Length > 300)
                        {
                            string txt = ord.AddressDeliveryLine1.Substring(0, 300);
                            ord.AddressDeliveryLine1 = txt;
                        }
                        break;

                    case 2:
                        ord.AddressDeliveryLine2 = xd.InnerText;                //  300
                        if (ord.AddressDeliveryLine2.Length > 300)
                        {
                            string txt = ord.AddressDeliveryLine2.Substring(0, 300);
                            ord.AddressDeliveryLine2 = txt;
                        }
                        break;

                    default:
                        break;
                    }
                }
                ord.AddressDeliveryTown     = dat.SingleNodeValidation_Text(del, "town", 150);              //  150
                ord.AddressDeliveryCounty   = dat.SingleNodeValidation_Text(del, "county", 150);            //  150
                ord.AddressDeliveryPostCode = dat.SingleNodeValidation_Text(del, "postcode", 30);           //  30
                ord.AddressDeliveryCountry  = dat.SingleNodeValidation_Text(del, "country", 200);           //  200
            }
            ord.FileName = fName + ".xml";

            string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(ord);

            /// ******************************************************************************
            /// Call Web Service    - "WebAccount"
            /// <param name="json2">Object serialized Json string.</param>
            /// <param name="fname">Xml file name </param>
            /// <param name="type">File Type (WebAccounts) </param>
            /// <returns>"rStatus" true if WebService was processed, else false</returns>
            /// Web service url is defined in the App.Config file
            /// ------------------------------------------------------------------------------
            rStatus = wsm.ConsumeWebService(json2, fName, syncRow.WebServiceAccounts, syncRow);
            //  <==============
            return(rStatus.IsOk);
        }
        public void StoreNewAccountDataLocally(WebAccount account)
        {
            if (account.Id != "")
            {
                ApplicationData.Current.LocalSettings.Values["AccountID"] = account.Id;
            }
            else
            {
                // It's a custom account
                ApplicationData.Current.LocalSettings.Values["AccountID"] = account.UserName;
            }


            ApplicationData.Current.LocalSettings.Values["ProviderID"] = account.WebAccountProvider.Id;
            if (account.WebAccountProvider.Authority != null)
            {
                ApplicationData.Current.LocalSettings.Values["Authority"] = account.WebAccountProvider.Authority;
            }
            else
            {
                ApplicationData.Current.LocalSettings.Values["Authority"] = "";
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected async override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = false;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.CreateDefaultUI();

            // Ensure the current window is active
            Window.Current.Activate();

            // Authenticate
            appSettings = ApplicationData.Current.RoamingSettings;
            App.WAP     = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", App.Authority);

            WebTokenRequest wtr = new WebTokenRequest(App.WAP, string.Empty, App.ClientId);
            wtr.Properties.Add("resource", App.Resource);

            // Check if there's a record of the last account used with the app
            var userID = appSettings.Values["userID"];
            if (userID != null)
            {
                // Get an account object for the user
                App.UserAccount = await WebAuthenticationCoreManager.FindAccountAsync(App.WAP, (string)userID);

                if (App.UserAccount != null)
                {
                    // Ensure that the saved account works for getting the token we need
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, App.UserAccount);

                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        App.UserAccount = wtrr.ResponseData[0].WebAccount;
                    }
                    else
                    {
                        // The saved account could not be used for getitng a token
                        MessageDialog messageDialog = new MessageDialog("We tried to sign you in with the last account you used with this app, but it didn't work out. Please sign in as a different user.");
                        await messageDialog.ShowAsync();

                        // Make sure that the UX is ready for a new sign in
                        UpdateUXonSignOut();
                    }
                }
                else
                {
                    // The WebAccount object is no longer available. Let's attempt a sign in with the saved username
                    wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString());
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);

                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        App.UserAccount = wtrr.ResponseData[0].WebAccount;
                    }
                }
            }
            else
            {
                // There is no recorded user. Let's start a sign in flow without imposing a specific account.
                WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);

                if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    App.UserAccount = wtrr.ResponseData[0].WebAccount;
                }
            }

            if (App.UserAccount != null) // we succeeded in obtaining a valid user
            {
                // save user ID in local storage
                UpdateUXonSignIn();
            }
            else
            {
                // nothing we tried worked. Ensure that the UX reflects that there is no user currently signed in.
                UpdateUXonSignOut();
                MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
                await messageDialog.ShowAsync();
            }

            // Run the tests
            Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(e.Arguments);
        }
Esempio n. 21
0
 private void UpdateWebAccount(WebAccount newAccount)
 {
     webAccount = newAccount;
     if (webAccount != null)
     {
         ApplicationData.Current.LocalSettings.Values["CurrentUserProviderId"] = webAccount.WebAccountProvider.Id;
         ApplicationData.Current.LocalSettings.Values["CurrentUserId"] = webAccount.Id;
     }
     else
     {
         ApplicationData.Current.LocalSettings.Values.Remove("CurrentUserProviderId");
         ApplicationData.Current.LocalSettings.Values.Remove("CurrentUserId");
     }            
 }
        public static IAsyncOperation <WebTokenRequestResult> RequestTokenWithWebAccountForWindowAsync(IntPtr hWnd, WebTokenRequest request, WebAccount webAccount)
        {
            IWebAuthenticationCoreManagerInterop webAuthenticationCoreManagerInterop = (IWebAuthenticationCoreManagerInterop)WindowsRuntimeMarshal.GetActivationFactory(typeof(WebAuthenticationCoreManager));
            Guid guid = typeof(IAsyncOperation <WebTokenRequestResult>).GUID;

            return(webAuthenticationCoreManagerInterop.RequestTokenWithWebAccountForWindowAsync(hWnd, request, webAccount, ref guid));
        }
        public async void AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID)
        {
            try
            {
                WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);

                // Azure Active Directory requires a resource to return a token
                if(Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations")
                {
                    webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
                }

                // 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 (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    defaultAccount = webTokenRequestResult.ResponseData[0].WebAccount;

                    button_GetTokenSilently.IsEnabled = true;
                    textblock_SignedInStatus.Text = "Signed in with:";
                    textblock_SignedInStatus.Foreground = new SolidColorBrush(Windows.UI.Colors.Green);
                    listview_SignedInAccounts.Items.Clear();
                    listview_SignedInAccounts.Items.Add(defaultAccount.Id);
                }

                OutputTokenResult(webTokenRequestResult);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage);
            }
        }
Esempio n. 24
0
 public bool TryGetAccountProperty(WebAccount webAccount, string propertyName, out string propertyValue)
 {
     return(webAccount.Properties.TryGetValue("Authority", out propertyValue));
 }
        // Get an access token for the given context and resourceId. An attempt is first made to 
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        public static async Task<string> GetTokenHelperAsync(WebAccountProvider accountProvider, string resourceId)
        {
            string token = null;
            WebAccountProvider aadAccountProvider;

            if (accountProvider != null)
            {
                aadAccountProvider = accountProvider;
            }
            else
            {
                aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                    AccountProviderId, Authority);

            }

            // Check if there's a record of the last account used with the app.
            var userID = settings.Values["userID"];

            WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId);
            webTokenRequest.Properties.Add("resource", resourceId);

            WebTokenRequestResult webTokenRequestResult;
            if (userID != null)
            {
                // Get an account object for the user.
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(aadAccountProvider, (string)userID);

                // Ensure that the saved account works for getting the token we need.
                webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount);
            }
            else
            {
                webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
            }

            if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch)
            {
                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;
                    settings.Values["userName"] = userAccount.Properties["DisplayName"];
                }

                return token;
            }
            else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
                webTokenRequest.Properties.Add("resource", resourceId);

                //get token through prompt
                if (userID != null)
                {
                    // Ensure that the saved account works for getting the token we need.
                    webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount);
                }
                else
                {
                    webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                }

                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    currentToken = webTokenResponse.Token;

                    if (userAccount != null)
                    {
                        // Save user ID in local storage.
                        settings.Values["userID"] = userAccount.Id;
                        settings.Values["userEmail"] = userAccount.UserName;
                        settings.Values["userName"] = userAccount.Properties["DisplayName"];
                    }
                    return token;
                }
                else
                {
                    // The saved account could not be used for getting a token.
                    // Make sure that the UX is ready for a new sign in.
                    await SignOutAsync();
                    return null;

                }
            }
            else
            {
                // The saved account could not be used for getting a token.
                // Make sure that the UX is ready for a new sign in.
                await SignOutAsync();
                return null;
            }

        }
        public static IAsyncOperation <WebTokenRequestResult> RequestTokenWithWebAccountForWindowAsync(IntPtr hWnd, WebTokenRequest request, WebAccount webAccount)
        {
            Guid iid = InteropHelper.GetIID <IAsyncOperation <WebTokenRequestResult> >();
            IWebAuthenticationCoreManagerInterop factory = InteropHelper.GetActivationFactory <IWebAuthenticationCoreManagerInterop>(typeof(WebAuthenticationCoreManager));

            return(factory.RequestTokenWithWebAccountForWindowAsync(hWnd, request, webAccount, ref iid));
        }
Esempio n. 27
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hiddenEntityId.Value == "") { Master.SetStatus("Save the record before adding a web user account.", 2); return; }
        if (isNew)
        {
            //string typ = Request.QueryString["type"];
            bool iscst = true;
            if (thisUserType != UserType.AccountCustomer) { iscst = false; }
            int entVal = Convert.ToInt32(hiddenEntityId.Value);
            if (Users.IsUsernameTaken(txtUserName.Text)) { Master.SetStatus("User name is taken. Select a new user name",2); return; }
            //Create new web account user
            try
            {
                LINQ_UsersDataContext dc = new LINQ_UsersDataContext();
                WebAccount wa = new WebAccount();
                wa.UserName = txtUserName.Text;
                wa.Password = Users.EncryptPass(txtPassword1.Text);
                wa.Email = txtEmail.Text;

                wa.AccountType = Users.GetUserChar(ddWebAccountType.SelectedItem.ToString());
                UpdateAccountRole(wa.id);
                wa.Active = true;
                wa.CreatedBy = (string)Session["username"];
                wa.DateOpen = DateTime.Now;
                wa.EmailVerified = false;
                wa.AccountType = Convert.ToChar(userChar);
                wa.FName = txtFName.Text;
                wa.LName = txtLName.Text;
                if (iscst) { wa.Customer = entVal; wa.Account = Users.GetCustomerAccountNumber(entVal); } else { wa.Employee = entVal; wa.Account = Users.GetEmployeeAccountNumber(entVal); }

                dc.WebAccounts.InsertOnSubmit(wa);
                dc.SubmitChanges();
                Users.CreateNewUserDashboard(wa.id, UserType.AccountCustomer);
                Users.SetupUserType(wa.id, Convert.ToChar(userChar));
                Master.SetStatus("Web account created for " + txtFName.Text + " " + txtLName.Text , 1);
            }
            catch (Exception ex)
            {
                Database.WriteException("Error adding web account. btnSave_Click", Page, HttpContext.Current, ex);
                Master.SetStatus("Unable to create web account" , 2);
            }

        }
        else
        {
            string new_username = txtUserName.Text;
            //Validate and then save to DB --- THIS IS ONLY A SAVE FOR THE WEB INFO, NOT THE employee or customer
            try
            {
                if (Users.IsUsernameTaken(new_username) && new_username != Users.GetUserName(thisUserId)) { Master.SetStatus("User name is already taken", 2); return; }
                LINQ_UsersDataContext dc = new LINQ_UsersDataContext();
                var userInfo = (from a in dc.WebAccounts
                                where a.id == Convert.ToInt32(thisUserId)
                                select a).FirstOrDefault();
                if (userInfo != null)
                {
                    if (new_username == "") { throw new NullReferenceException("Change UserName"); }
                    //set vals and update
                    userInfo.FName = txtFName.Text;
                    userInfo.LName = txtLName.Text;
                    userInfo.Email = txtEmail.Text;
                    userInfo.UserName = txtUserName.Text;
                    userInfo.AccountType = Users.GetUserChar(ddWebAccountType.SelectedItem.ToString());
                    UpdateAccountRole(userInfo.id);

                    dc.SubmitChanges();
                    Master.SetStatus("Web account user updated", 1);
                    btnSave.Visible = false;
                    btnEditUser.Visible = true;
                    txtUserName.ReadOnly = true;
                }
            }
            catch (Exception ex)
            {
                Database.WriteException("Error updating WebUser information. btnSave_Click", Page, HttpContext.Current, ex);
                Master.SetStatus("Error updating web account information", 2);
            }
        }
    }
Esempio n. 28
0
        public async Task ATS_AccountWithWamId_Async()
        {
            // Arrange
            using (MockHttpAndServiceBundle harness = CreateTestHarness())
            {
                _webAccountProviderFactory.ClearReceivedCalls();

                var wamAccountProvider = new WebAccountProvider("id", "*****@*****.**", null);
                var extraQP            = new Dictionary <string, string>()
                {
                    { "extraQp1", "extraVal1" }, { "instance_aware", "true" }
                };
                var requestParams = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityHomeTenant,
                    extraQueryParameters: extraQP,
                    validateAuthority: true); // AAD
                requestParams.UserConfiguredAuthority = Authority.CreateAuthority("https://login.microsoftonline.com/organizations");

                requestParams.Account = new Account(
                    $"{TestConstants.Uid}.{TestConstants.Utid}",
                    TestConstants.DisplayableId,
                    null,
                    new Dictionary <string, string>()
                {
                    { TestConstants.ClientId, "wam_id_1" }
                });                                                                               // account has wam_id!

                var webAccount              = new WebAccount(wamAccountProvider, "*****@*****.**", WebAccountState.Connected);
                var webTokenRequest         = new WebTokenRequest(wamAccountProvider);
                var webTokenResponseWrapper = Substitute.For <IWebTokenRequestResultWrapper>();
                webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
                var webTokenResponse = new WebTokenResponse();
                webTokenResponseWrapper.ResponseData.Returns(new List <WebTokenResponse>()
                {
                    webTokenResponse
                });

                _webAccountProviderFactory.GetAccountProviderAsync(null).ReturnsForAnyArgs(Task.FromResult(wamAccountProvider));
                _wamProxy.FindAccountAsync(Arg.Any <WebAccountProvider>(), "wam_id_1").Returns(Task.FromResult(webAccount));
                _aadPlugin.CreateWebTokenRequestAsync(
                    wamAccountProvider,
                    requestParams,
                    isForceLoginPrompt: false,
                    isAccountInWam: true,
                    isInteractive: false)
                .Returns(Task.FromResult(webTokenRequest));

                var atsParams = new AcquireTokenSilentParameters();

                _wamProxy.GetTokenSilentlyAsync(webAccount, webTokenRequest).
                Returns(Task.FromResult(webTokenResponseWrapper));

                _aadPlugin.ParseSuccessfullWamResponse(webTokenResponse, out _).Returns(_msalTokenResponse);

                // Act
                var result = await _wamBroker.AcquireTokenSilentAsync(requestParams, atsParams).ConfigureAwait(false);

                // Assert
                Assert.AreSame(_msalTokenResponse, result);
                Assert.AreEqual("yes", webTokenRequest.Properties["validateAuthority"]);
                Assert.AreEqual("extraVal1", webTokenRequest.Properties["extraQp1"]);

                // Although at the time of writing, MSAL does not support instance aware ...
                // WAM does support it but the param is different - discovery=home
                Assert.AreEqual("home", webTokenRequest.Properties["discover"]);
                Assert.AreEqual("https://login.microsoftonline.com/organizations/", webTokenRequest.Properties["authority"]);
            }
        }
        public void StoreNewAccountDataLocally(WebAccount account)
        {
            ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];

            if (account.Id != "")
            {
                accountsContainer.Containers[ProviderIdSubContainer].Values[account.Id] = account.WebAccountProvider.Id;
                accountsContainer.Containers[AuthoritySubContainer].Values[account.Id] = account.WebAccountProvider.Authority;
            }
            else
            {
                accountsContainer.Containers[ProviderIdSubContainer].Values[account.UserName] = account.WebAccountProvider.Id;
            }

        }
 // Change the currently signed in user
 private async void btnSignInOut_Click(object sender, RoutedEventArgs e)
 {
     // prepare a request with 'WebTokenRequestPromptType.ForceAuthentication', 
     // which guarantees that the user will be able to enter an account of their choosing
     // regardless of what accounts are already present on the system
     WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
     wtr.Properties.Add("resource", resource);
     WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
     if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
     {
         userAccount = wtrr.ResponseData[0].WebAccount;
         UpdateUXonSignIn();
     }
     else
     {
         UpdateUXonSignOut();
         MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
         await messageDialog.ShowAsync();
     }
 }
Esempio n. 31
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();

        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority);
            appSettings = ApplicationData.Current.RoamingSettings;                               
            WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId);
            wtr.Properties.Add("resource", resource);
            
            // Check if there's a record of the last account used with the app
            var userID = appSettings.Values["userID"];
            if (userID != null)
            {
                // Get an account object for the user
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(wap, (string)userID);
                if (userAccount != null)
                {
                    // Ensure that the saved account works for getting the token we need
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, userAccount);
                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {                        
                        userAccount = wtrr.ResponseData[0].WebAccount;
                    }
                    else
                    {                        
                        // The saved account could not be used for getitng a token
                        MessageDialog messageDialog = new MessageDialog("We tried to sign you in with the last account you used with this app, but it didn't work out. Please sign in as a different user.");
                        await messageDialog.ShowAsync();
                        // Make sure that the UX is ready for a new sign in
                        UpdateUXonSignOut();
                    }
                }
                else
                {
                    // The WebAccount object is no longer available. Let's attempt a sign in with the saved username
                    wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString());
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {                        
                        userAccount = wtrr.ResponseData[0].WebAccount;
                    }
                }
            }
            else
            {  
                // There is no recorded user. Let's start a sign in flow without imposing a specific account.                             
                WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    userAccount = wtrr.ResponseData[0].WebAccount;
                }
            }

            if (userAccount != null) // we succeeded in obtaining a valid user
            {
                // save user ID in local storage
                UpdateUXonSignIn();
            }
            else
            {
                // nothing we tried worked. Ensure that the UX reflects that there is no user currently signed in.
                UpdateUXonSignOut();
                MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
                await messageDialog.ShowAsync();                
            }
        }
        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();
        }
Esempio n. 34
0
        public async Task FetchTransferTokenAsync()
        {
            // Arrange
            using (MockHttpAndServiceBundle harness = CreateTestHarness())
            {
                var msaProvider = new WebAccountProvider("id", "*****@*****.**", null);

                Client.Internal.Requests.AuthenticationRequestParameters requestParams =
                    harness.CreateAuthenticationRequestParameters(
                        TestConstants.AuthorityHomeTenant,
                        validateAuthority: true);
                requestParams.AppConfig.WindowsBrokerOptions = new WindowsBrokerOptions()
                {
                    MsaPassthrough = true
                };
                var msaRequest = new WebTokenRequest(msaProvider);
                // step 1 - msa request
                _msaPlugin.CreateWebTokenRequestAsync(msaProvider, requestParams, false, true, false)
                .Returns(Task.FromResult(msaRequest));

                var webTokenResponseWrapper = Substitute.For <IWebTokenRequestResultWrapper>();
                webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
                WebAccount accountFromMsaProvider = new WebAccount(msaProvider, "*****@*****.**", WebAccountState.Connected);
                var        webTokenResponse       = new WebTokenResponse("v1_token", accountFromMsaProvider);
                webTokenResponseWrapper.ResponseData.Returns(new List <WebTokenResponse>()
                {
                    webTokenResponse
                });
                _wamProxy.RequestTokenForWindowAsync(IntPtr.Zero, msaRequest).Returns(webTokenResponseWrapper);

                // step 2 - we have v1 token and a WebAccount, now get a transfer token
                var transferTokenRequest = new WebTokenRequest(msaProvider);
                _msaPlugin
                .CreateWebTokenRequestAsync(
                    msaProvider,
                    TestConstants.ClientId,
                    MsaPassthroughHandler.TransferTokenScopes)
                .Returns(Task.FromResult(transferTokenRequest));
                var webTokenResponseWrapper2   = Substitute.For <IWebTokenRequestResultWrapper>();
                var transferTokenRequestResult = Substitute.For <IWebTokenRequestResultWrapper>();
                transferTokenRequestResult.ResponseStatus.Returns(WebTokenRequestStatus.Success);
                //WebAccount accountFromMsaProvider = new WebAccount(msaProvider, "*****@*****.**", WebAccountState.Connected);
                var transferTokenResponse = new WebTokenResponse("transfer_token");
                webTokenResponseWrapper2.ResponseData.Returns(new List <WebTokenResponse>()
                {
                    transferTokenResponse
                });
                _msaPlugin.ParseSuccessfullWamResponse(Arg.Any <WebTokenResponse>(), out Arg.Any <Dictionary <string, string> >())
                .Returns(x =>
                {
                    x[1] = new Dictionary <string, string>();
                    (x[1] as Dictionary <string, string>).Add("code", "actual_transfer_token");
                    return(new MsalTokenResponse());
                });

                _wamProxy.RequestTokenForWindowAsync(IntPtr.Zero, transferTokenRequest).Returns(webTokenResponseWrapper2);

                // Act
                var transferToken = await _msaPassthroughHandler.TryFetchTransferTokenAsync(requestParams, msaProvider)
                                    .ConfigureAwait(false);

                // Assert
                Assert.AreEqual("actual_transfer_token", transferToken);
            }
        }