Retrieve() public method

public Retrieve ( [ resource, [ userName ) : PasswordCredential
resource [
userName [
return PasswordCredential
Ejemplo n.º 1
0
        public Storage(string fileName) {
            this.fileName = new String(fileName.ToCharArray());
            PasswordVault vault = new PasswordVault();

            try {
                this.password = vault.Retrieve(Conf.resource, Conf.username).Password;
            }
            catch (Exception e) {
                vault.Add(new PasswordCredential(Conf.resource, Conf.username, CryptographicBuffer.EncodeToBase64String(CryptographicBuffer.GenerateRandom(64))));
                this.password = vault.Retrieve(Conf.resource, Conf.username).Password;
            }
        }
        private void ButtonEnterPin_Click(object sender, RoutedEventArgs e)
        {
            string PinCrypt = MakeCryptSHA512(PinCodePasswordBox.Password);

            #region  ПОЛУЧИТЬ ПИН ИЗ ХРАНИЛИЩА
            var vault    = new Windows.Security.Credentials.PasswordVault();
            var SavedPIN = vault.Retrieve(resourceName, defaultUserName);
            #endregion

            if (PinCrypt == SavedPIN.Password)
            {
                MainScrollViewer.Background   = new SolidColorBrush(Windows.UI.Colors.White);
                ContentFrame.Background       = new SolidColorBrush(Windows.UI.Colors.White);
                ContentFrame.Visibility       = Windows.UI.Xaml.Visibility.Visible;
                MenuListBox.Visibility        = Windows.UI.Xaml.Visibility.Visible;
                HamburgerButton.Visibility    = Windows.UI.Xaml.Visibility.Visible;
                StackPanelEnterPIN.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                ButtonEnterPin.Visibility     = Windows.UI.Xaml.Visibility.Collapsed;
                StatusPIN.Visibility          = Windows.UI.Xaml.Visibility.Collapsed;
                ContentFrame.Navigate(typeof(QuickPage));
            }
            else
            {
                StatusPIN.Text = "Неверный ПИН-код. Попробуйте ещё раз.";
            }
        }
Ejemplo n.º 3
0
        private void SelectUser_Click(object sender, SelectionChangedEventArgs e)
        {
            Page        outputFrame        = (Page)rootPage.OutputFrame.Content;
            Page        inputFrame         = (Page)rootPage.InputFrame.Content;
            TextBox     InputUserNameValue = outputFrame.FindName("InputUserNameValue") as TextBox;
            PasswordBox InputPasswordValue = outputFrame.FindName("InputPasswordValue") as PasswordBox;
            ComboBox    SelectUser         = inputFrame.FindName("SelectUser") as ComboBox;

            try
            {
                if (SelectUser.SelectedIndex > 1)
                {
                    InputUserNameValue.Text = SelectUser.SelectedItem.ToString();

                    Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
                    PasswordCredential cred = vault.Retrieve("Scenario 2", (String)SelectUser.SelectedItem);
                    if (cred.Password != "")
                    {
                        InputPasswordValue.Password = cred.Password;
                    }
                }
            }
            catch (Exception Error)
            {
                //
                // Bad Parameter, Machine infor Unavailable errors are to be handled here.
                //
                DebugPrint(Error.ToString());
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Attempt to sign in to GitHub using the credentials supplied. 
        /// </summary>
        /// <param name="username">GitHub username</param>
        /// <param name="password">GitHub password</param>
        /// <param name="cached">Whether these credentials came from local storage</param>
        /// <returns>true if successful, false otherwise</returns>
        public async Task<string> Login(string username, string password, bool cached = false)
        {
            client.Credentials = new Credentials(username, password);
            try
            {
                //hacky way of determining whether the creds are correct
                await client.GitDatabase.Reference.Get("dhbrett", "Graffiti", "heads/master");
                //we haven't thrown so all good
                SignedIn = true;

                //these are new credentials, save them
                if (!cached)
                {
                    var pv = new PasswordVault();
                    pv.Add(new PasswordCredential { Resource = RESOURCE, UserName = username, Password = password });

                    localSettings.Values[USERNAME] = username;
                }

                return "pass";
            }
            catch(Exception e)
            {
                if (e.Message.Contains("two-factor"))
                {
                    return "tfa";
                }
                else if (cached)
                {
                    var pv = new PasswordVault();
                    pv.Remove(pv.Retrieve(RESOURCE, username));
                }
                return "fail";
            }
        }
Ejemplo n.º 5
0
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            TextBox InputResourceValue = rootPage.FindName("InputResourceValue") as TextBox;
            TextBox InputUserNameValue = rootPage.FindName("InputUserNameValue") as TextBox;
            String  result             = "";

            if (InputResourceValue.Text == "" || InputUserNameValue.Text == "")
            {
                DebugPrint("Inputs are missing. Resource and Username are required.");
            }
            else
            {
                try
                {
                    //
                    //this is the code to remove a credentialt from PasswordVault by supplying resource or username
                    //
                    Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
                    PasswordCredential cred = vault.Retrieve(InputResourceValue.Text, InputUserNameValue.Text);
                    vault.Remove(cred);
                    result = "Credential removed successfully. Resource: " + InputResourceValue.Text + " Username: "******".";
                    DebugPrint(result.ToString());
                }
                catch (Exception Error) // No stored credentials, so none to delete
                {
                    DebugPrint(Error.Message);
                }
            }
        }
Ejemplo n.º 6
0
        private dynamic SecureLoadPassword(string username)
        {
            // Credential Lockerから資格情報を取得する
            PasswordVault vault = new PasswordVault();
            PasswordCredential credential = vault.Retrieve(RESOURCE, username);

            return new { UserName = credential.UserName, Password = credential.Password };
        }
Ejemplo n.º 7
0
        public string RetrievePassword(string resource, string userName)
        {
            //find credentials in the store
            PasswordCredential credential = null;

            try
            {
                // Try to get an existing credential from the vault.
                credential = _passwordVault.Retrieve(resource, userName);
            }
            catch (Exception)
            {
                // When there is no matching resource an error occurs, which we ignore.
            }
            credential?.RetrievePassword();
            return(credential?.Password);
        }
Ejemplo n.º 8
0
        public static string GetPassword()
        {
            PasswordVault passwordVault = new PasswordVault();
            if (!passwordVault.RetrieveAll().Any(credential => credential.UserName == UserNameText && credential.Resource == ResourceText))
            {
                SetPassword();
            }

            return passwordVault.Retrieve(ResourceText, UserNameText).Password;
        }
Ejemplo n.º 9
0
        private void SettingsCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            SettingsCommand about_cmd = new SettingsCommand("about", "About", (x) =>
            {
                _settingsPopup = new Popup();
                _settingsPopup.Closed += OnPopupClosed;
                Window.Current.Activated += OnWindowActivated;
                _settingsPopup.IsLightDismissEnabled = true;
                _settingsPopup.Width = _settingsWidth;
                _settingsPopup.Height = _windowBounds.Height;

                SettingsAboutView mypane = new SettingsAboutView();
                //SimpleSettingsNarrow mypane = new SimpleSettingsNarrow();
                mypane.Width = _settingsWidth;
                mypane.Height = _windowBounds.Height;

                _settingsPopup.Child = mypane;
                _settingsPopup.SetValue(Canvas.LeftProperty, _windowBounds.Width - _settingsWidth);
                _settingsPopup.SetValue(Canvas.TopProperty, 0);
                _settingsPopup.IsOpen = true;
            });

            args.Request.ApplicationCommands.Add(about_cmd);

            SettingsCommand logout_cmd = new SettingsCommand("logout", "Log out", (x) =>
            {
                var vault = new PasswordVault();
                vault.Remove(vault.Retrieve("Sovok.tv WinApp", App.ViewModel.UserAccount.login));
                bool nav = Frame.Navigate(typeof(Login));
                App.ViewModel = new Model.MainViewModel();
            });

            args.Request.ApplicationCommands.Add(logout_cmd);

            SettingsCommand settings_cmd = new SettingsCommand("settings", "Settings", (x) =>
            {
                _settingsPopup = new Popup();
                _settingsPopup.Closed += OnPopupClosed;
                Window.Current.Activated += OnWindowActivated;
                _settingsPopup.IsLightDismissEnabled = true;
                _settingsPopup.Width = _settingsWidth;
                _settingsPopup.Height = _windowBounds.Height;

                SettingsView mypane = new SettingsView();
                mypane.Width = _settingsWidth;
                mypane.Height = _windowBounds.Height;

                _settingsPopup.Child = mypane;
                _settingsPopup.SetValue(Canvas.LeftProperty, _windowBounds.Width - _settingsWidth);
                _settingsPopup.SetValue(Canvas.TopProperty, 0);
                _settingsPopup.IsOpen = true;
            });
            args.Request.ApplicationCommands.Add(settings_cmd);
        }
 public string Retrieve(string key)
 {
     try
     {
         var vault = new PasswordVault();
         return vault.Retrieve(key, "username").Password;
     }
     catch
     {
         return null;
     }
 }
Ejemplo n.º 11
0
 public static PasswordCredential RetrieveCredential(string username)
 {
     try
     {
         PasswordVault vault = new PasswordVault();
         return vault.Retrieve(CredentialSource, username);
     }
     catch
     {
         return null;
     }
 }
Ejemplo n.º 12
0
 public string Unprotect(string key)
 {
     try
     {
         var vault = new PasswordVault();
         return vault.Retrieve(Package.Current.Id.Name, key).Password;
     }
     catch
     {
         return null;
     }
 }
Ejemplo n.º 13
0
 public string GetStoredPassword()
 {
     try
     {
         var passwordValut = new Windows.Security.Credentials.PasswordVault();
         var creds         = passwordValut.Retrieve(RESOURCE, Username);
         return(creds.Password);
     }
     catch
     {
         return(null);
     }
 }
Ejemplo n.º 14
0
        public static async Task ClearCurrentUser()
        {
            string sessionKey = CurrentUser.SessionKey;
            await UsersPersister.Logout(sessionKey);
            var vault = new PasswordVault();
            vault.Remove(vault.Retrieve(UserCredentialsToken, CurrentUser.Username));


            localSettings.Values["ProfilePictureUrl"] = "";
            localSettings.Values["FirstName"] = "";
            localSettings.Values["LastName"] = "";
            localSettings.Values["Reputation"] = "";
        }
Ejemplo n.º 15
0
 /// <summary>
 ///     Removes the password from the secure storage.
 /// </summary>
 public void RemovePassword()
 {
     // If there where no element to remove it will throw a com exception who we handle.
     try
     {
         var vault = new PasswordVault();
         var passwordCredential = vault.Retrieve(Package.Current.Id.Name, PASSWORD_KEY);
         vault.Remove(passwordCredential);
     }
     catch (Exception)
     {
     }
 }
        /// <summary>
        /// Load previously stored credentials from the password vault, if any
        /// </summary>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        private async static Task <PasswordParameter> LoadDatabasePasswordAsync(string databaseName)
        {
            var vault = new Windows.Security.Credentials.PasswordVault();
            PasswordCredential cred = vault.Retrieve(databaseName, PASSWORD_VAULT_USER_NAME);

            // Also try to retrieve the KeyFile, if any was saved
            StorageFile keyFile = await PasswordDialogViewModel.GetStoredKeyFileAsync(databaseName);

            return(new PasswordParameter()
            {
                Password = cred.Password,
                KeyFile = keyFile
            });
        }
Ejemplo n.º 17
0
        public static async Task<bool> TryAuthenticateSilently(bool useCachedCredentials = true)
        {
            MobileServiceUser user = null;

            var vault = new PasswordVault();

            PasswordCredential savedCredentials = null;

            if (useCachedCredentials && LegacyUserId.Value != null)
            {
                try
                {
                    savedCredentials = vault.FindAllByResource(ProviderId).FirstOrDefault();
                }
                catch (Exception)
                {
                    // No credentials found.
                }
            }

            if (savedCredentials != null)
            {
                user = new MobileServiceUser(savedCredentials.UserName)
                {
                    MobileServiceAuthenticationToken = vault.Retrieve(ProviderId, savedCredentials.UserName).Password
                };

                MobileService.Client.CurrentUser = user;
            }

            if (user == null)
            {
                try
                {
                    user = await DoLoginAsync(CredentialPromptType.DoNotPrompt);
                }
                catch (Exception)
                {
                    // Do nothing
                }

                if (user != null)
                {
                    vault.Add(new PasswordCredential(ProviderId, user.UserId, user.MobileServiceAuthenticationToken));
                }
            }

            return user != null;
        }
Ejemplo n.º 18
0
        public void LoadToken()
        {
            if (this.IsFirst) { return; }

            try
            {
                var p = new PasswordVault();
                var accessToken = p.Retrieve("TwitterAppSample.AccessToken", this.ScreenName);
                var accessTokenSecret = p.Retrieve("TwitterAppSample.AccessTokenSecret", this.ScreenName);

                this.tokens = Tokens.Create(
                    Constants.ConsumerKey,
                    Constants.ConsumerSecret,
                    accessToken.Password,
                    accessTokenSecret.Password);

                this.tokens.Followers.ListAsync();
                this.OnPropertyChanged(() => this.IsAuth);
            }
            catch
            {
                // ignore
            }
        }
 public PasswordCredential GetSavedCredentials(string resource) {
     try {
         var vault = new PasswordVault();
         var credentials = vault.FindAllByResource(resource);
         var cred = credentials.FirstOrDefault();
         if (cred != null)
             return vault.Retrieve(resource, cred.UserName);
         else
             return null;
     }
     // The password vault throws System.Exception if no credentials have been stored with this resource.
     catch (Exception) {
         return null;
     }
 }
Ejemplo n.º 20
0
        private PasswordCredential GetCredentialsFromVault(PasswordVault vault)
        {
            PasswordCredential credentials;
            try
            {
                credentials = vault.FindAllByResource(PasswordVaultResourceName).FirstOrDefault();
                credentials = vault.Retrieve(PasswordVaultResourceName, credentials.UserName);
            }
            catch (Exception exception)
            {
                credentials = null;
                this.Log(exception);
            }

            return credentials;
        }
Ejemplo n.º 21
0
		public static async Task LogOff() {
			var vault = new PasswordVault();
			const string vaultResource = "S2M";

			var credentialList = vault.FindAllByResource(vaultResource);

			if (credentialList.Any()) {
				var credentials = credentialList.First();
				var username = credentials.UserName;
				var password = vault.Retrieve(vaultResource, username).Password;

				vault.Remove(new PasswordCredential(vaultResource, username, password));
			}

			await Common.StorageService.DeleteObjectAsync("Profile");
		}
Ejemplo n.º 22
0
		/// <summary>
		/// Creates a new LastFmScrobbler.
		/// </summary>
		private LastFmScrobbler()
		{
			try
			{
				PasswordVault vault = new PasswordVault();
				PasswordCredential cred = vault.FindAllByResource(PASSWORD_STORE).FirstOrDefault();
				if (cred != null)
				{
					_username = cred.UserName;
					_session = vault.Retrieve(PASSWORD_STORE, _username).Password;
				}
			}
			catch (Exception)
			{
				// Justification: PaswordVault / PasswordCredential throw exception when no password found
			}
		}
Ejemplo n.º 23
0
        private PasswordCredential GetCredential(string app, string userName)
        {
            var vault = new PasswordVault();
            try
            {
                var credential = vault.FindAllByResource(app).FirstOrDefault(c => c.UserName == userName);
                if (credential != null)
                {
                    return vault.Retrieve(app, userName);
                }
            }
            catch (Exception)
            {
                // If no credentials have been stored with the given name, an exception is thrown.
            }

            return null;
        }
Ejemplo n.º 24
0
        private async Task <bool> RenewAccessToken()
        {
            var    vault = new Windows.Security.Credentials.PasswordVault();
            string login = GetUserLogin(ArelAPI.DataStorage.getData("user"));

            //si le login est le string de fallback, on a pas d'user enregistré => échec
            if (login == "user")
            {
                return(false);
            }

            PasswordCredential passwd = vault.Retrieve("ARELUWP_User", login);

            bool result = await LoginARELUser(login, passwd.Password);

            //Si result = true, un nouvel access token a été stocké.
            return(result);
        }
        public static PasswordCredential GetCredential()
        {
            PasswordCredential passwordCredential = null;
            PasswordVault passwordVault = new PasswordVault();
            try
            {
                passwordCredential = passwordVault.FindAllByResource(RESOURCE).FirstOrDefault();
                if (passwordCredential != null)
                {
                    passwordCredential.Password = passwordVault.Retrieve(RESOURCE, passwordCredential.UserName).Password;
                }
            }
            catch (Exception)
            {
                //TODO: implement error handling
            }

            return passwordCredential;
        }
Ejemplo n.º 26
0
        public static string GetUsernameFromLocker()
        {
            try
            {
                var vault = new PasswordVault();
                var credentialList = vault.FindAllByResource(ResourceName);

                if (credentialList.Count <= 0)
                    return "";

                var credential = credentialList[0];
                var fullCredential = vault.Retrieve(credential.Resource, credential.UserName);

                return fullCredential.UserName;
            }
            catch
            {
                return "";
            }
        }
Ejemplo n.º 27
0
        public static MobileCredentials GetCredentialFromLocker()
        {
            try
            {
                var vault = new PasswordVault();
                var credentialList = vault.FindAllByResource(ResourceName);

                if (credentialList.Count <= 0)
                    return null;

                var credential = credentialList[0];
                var fullCredential = vault.Retrieve(credential.Resource, credential.UserName);

                var credentials = new MobileCredentials(fullCredential.UserName, fullCredential.Password);
                return credentials;
            }
            catch
            {
                return null;
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            string userName, password;
            bool saveCredentials = false;
            PasswordCredential credential = null;

            AnimationLibrary.AnimateOpacity(this.background, 1.0, 2.0);
            AnimationLibrary.AnimateX(this.logo, -275, 0.5);

            try
            {
                var passwordVault = new PasswordVault();
                credential = passwordVault.FindAllByResource("Music8")[0];
                credential = passwordVault.Retrieve("Music8", credential.UserName);
            }
            catch (Exception exception) { }

       
            if (credential == null)
            {
                CredentialPickerOptions credPickerOptions = new CredentialPickerOptions();
                credPickerOptions.Message = "Enter your Google Music credentials";
                credPickerOptions.Caption = "Login to Music8";
                credPickerOptions.TargetName = ".";
                credPickerOptions.AlwaysDisplayDialog = true;
                credPickerOptions.AuthenticationProtocol = AuthenticationProtocol.Basic;
                var credPickerResults = await CredentialPicker.PickAsync(credPickerOptions);

                userName = credPickerResults.CredentialUserName;
                password = credPickerResults.CredentialPassword;
                saveCredentials = credPickerResults.CredentialSaveOption == CredentialSaveOption.Selected;
            }
            else
            {
                userName = credential.UserName;
                password = credential.Password;
            }

            DoLogin(userName, password, saveCredentials);
        }
        public MainPage()
        {
            this.InitializeComponent();

            MenuListBox.Visibility     = Windows.UI.Xaml.Visibility.Collapsed;
            HamburgerButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            try
            {
                #region ПОПЫТАТЬСЯ ПОЛУЧИТЬ ПИН ИЗ ХРАНИЛИЩА
                var vault    = new Windows.Security.Credentials.PasswordVault();
                var SavedPIN = vault.Retrieve(resourceName, defaultUserName);
                #endregion
            }

            catch
            {
                StackPanelEnterPIN.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                ButtonEnterPin.Visibility     = Windows.UI.Xaml.Visibility.Collapsed;
                StackPanelSETUPPIN.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
        }
        public static Tuple<string, string> getCredential()
        {
            var vault = new PasswordVault();

            Tuple<string, string> credential = null;

            try {
                var creds = vault.FindAllByResource(VAULT_RESOURCE).FirstOrDefault();
                if (creds != null)
                {
                    String username = creds.UserName;
                    String password = vault.Retrieve(VAULT_RESOURCE, username).Password;
                    credential = new Tuple<string, string>(username, password);
                }
                
            } catch (Exception e){

            }

            return credential;
           
        }
 private void ClearVault()
 {
     try
     {
         var vault = new PasswordVault();
         var cred = vault.Retrieve(_resourceName, "token");
         vault.Remove(cred);
     }
     catch { }
 }
Ejemplo n.º 32
0
        public async Task<TunesUser> SignInUser(string userName, string password)
        {
            TunesUser tunesUser = null;
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                string strUrl = string.Format("{0}/token", this.ServiceUrl);

                var authClient = new OAuth2Client(
                    new Uri(strUrl),
                    "BSEtunes",
                    OAuthClientSercret);
                try
                {
                    this.TokenResponse = await authClient.RequestResourceOwnerPasswordAsync(userName, password);
                    if (this.TokenResponse != null)
                    {
						//if (this.TokenResponse..IsError)
						//{
						//	throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage);
						//}

                        Windows.Storage.ApplicationData.Current.RoamingSettings.Values["username"] = userName;

                        Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
                        PasswordCredential passwordCredential = new PasswordCredential(PasswordVaultResourceName, userName, password);
                        vault.Add(passwordCredential);

                        if (passwordCredential != null)
                        {
                            tunesUser = this.User = new TunesUser
                            {
                                UserName = userName,
                                Password = vault.Retrieve(PasswordVaultResourceName, passwordCredential.UserName).Password
                            };
                        }
                    }
                }
                catch (Exception)
                {
                    throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage);
                }
            }
            else
            {
                throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage);
            }
            return tunesUser;
        }
Ejemplo n.º 33
0
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            TextBox InputResourceValue = rootPage.FindName("InputResourceValue") as TextBox;
            TextBox InputUserNameValue = rootPage.FindName("InputUserNameValue") as TextBox;
            String result = "";
            if (InputResourceValue.Text == "" || InputUserNameValue.Text == "")
            {
                DebugPrint("Inputs are missing. Resource and Username are required.");
            }
            else
            {
                try
                {
                    //
                    //this is the code to remove a credentialt from PasswordVault by supplying resource or username
                    //
                    Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
                    PasswordCredential cred = vault.Retrieve(InputResourceValue.Text, InputUserNameValue.Text);
                    vault.Remove(cred);
                    result = "Credential removed successfully. Resource: " + InputResourceValue.Text + " Username: "******".";
                    DebugPrint(result.ToString());
                }
                catch (Exception Error) // No stored credentials, so none to delete
                {
                    DebugPrint(Error.Message);
                }
            }

        }
Ejemplo n.º 34
0
        private void Read_Click(object sender, RoutedEventArgs e)
        {
            TextBox InputResourceValue = rootPage.FindName("InputResourceValue") as TextBox;
            TextBox InputUserNameValue = rootPage.FindName("InputUserNameValue") as TextBox;
            String result = "";

            try
            {
                //
                //Read a credential from PasswordVault by supplying resource or username
                //
                Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
                IReadOnlyList<PasswordCredential> creds = null;
                PasswordCredential cred = null;

                //
                //If both resource and username are empty, you can use RetrieveAll() to enumerate all credentials
                //
                if (InputUserNameValue.Text == "" && InputResourceValue.Text == "")
                {
                    DebugPrint("Retrieving all credentials since resource or username are not specified.");
                    creds = vault.RetrieveAll();
                }
                //
                //If there is only resouce, you can use FindAllByResource() to enumerate by resource. 
                //Note: the password will not be returned, you need to call retrieveAll with returned resouce and username to get the credential with password
                //
                else if (InputUserNameValue.Text == "")
                {
                    DebugPrint("Retrieve credentials by resouces that you provided");
                    creds = vault.FindAllByResource(InputResourceValue.Text);      
                }
                //
                //If there is only username, you can use findbyusername() to enumerate by resource. 
                //Note: the password will not be returned, you need to call retrieveAll with returned resouce and username to get the credential with password 
                //
                else if (InputResourceValue.Text == "")
                {
                    DebugPrint("Retrieve credentials by username that you provided"); 
                    creds = vault.FindAllByUserName(InputUserNameValue.Text);
                }
                //
                //Read by explicit resource and username name, result will be a single credential if it exists. Password will be returned.
                //
                else
                    cred = vault.Retrieve(InputResourceValue.Text, InputUserNameValue.Text);

                //
                //Output credential added to debug spew
                //
                if (creds != null)
                {
                    DebugPrint("There are " + creds.Count + " credential(s) found.");
                    foreach (PasswordCredential c in creds)
                    {
                        try
                        {
                            PasswordCredential c1 = vault.Retrieve(c.Resource.ToString(), c.UserName.ToString());
                            result = "Credential read successfully. " + "Resource: " + c.Resource.ToString() + ", " + "Username: "******"Password: "******".";
                            DebugPrint(result.ToString());
                        }
                        catch (Exception Error)
                        {
                            DebugPrint(Error.Message);
                        }
                    }
                }

                else if (cred != null)
                {
                    result = "Credential read successfully. " + "Resource: " + cred.Resource + ", " + "Username: "******"Password: "******".";
                    DebugPrint(result.ToString());
                }
                else
                {
                    result = "Credential not found.";
                    DebugPrint(result.ToString());
                }

                
            }
            catch (Exception Error) // No stored credentials, so none to delete
            {
                if (Error.HResult == -2147023728)
                    DebugPrint("Credential not found.");
                else
                    DebugPrint(Error.Message);
            }
            

        }
        private async void PasswordVaultRemoverMethod(object obj)
        {
            switch (int.Parse(obj.ToString()))
            {
                case 1:
                    var vault = new PasswordVault();
                    try
                    {
                        var credentialList = vault.FindAllByUserName("TwitterAccessToken");
                        if (credentialList.Count <= 0) return;
                        var credential = vault.Retrieve("Friend", "TwitterAccessToken");
                        vault.Remove(new PasswordCredential("Friend", "TwitterAccessToken", credential.Password));
                        var credentialList1 = vault.FindAllByUserName("TwitterAccessTokenSecret");
                        if (credentialList1.Count <= 0) return;
                        var credential1 = vault.Retrieve("Friend", "TwitterAccessTokenSecret");
                        vault.Remove(new PasswordCredential("Friend", "TwitterAccessTokenSecret", credential1.Password));
                        TwitterPlusIconVisibility = Visibility.Visible;
                        TwitterRemoveIconVisibility = Visibility.Collapsed;
                    }

                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                    }
                    break;

                case 2:
                    var sess = FBSession.ActiveSession;
                    await sess.LogoutAsync();
                    FacebookPlusIconVisibility = Visibility.Visible;
                    FacebookRemoveIconVisibility = Visibility.Collapsed;
                    break;

                default:
                    break;
            }
            RaisePropertyChanged(() => TwitterRemoveIconVisibility);
            RaisePropertyChanged(() => TwitterPlusIconVisibility);
            RaisePropertyChanged(()=>FacebookPlusIconVisibility);
            RaisePropertyChanged(()=>FacebookRemoveIconVisibility);
        }
        private void Read_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Read a credential from PasswordVault by supplying resource or username
                Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
                IReadOnlyList <PasswordCredential>         creds = null;
                PasswordCredential cred = null;

                //If both resource and username are empty, you can use RetrieveAll() to enumerate all credentials
                if (InputUserNameValue.Text == "" && InputResourceValue.Text == "")
                {
                    rootPage.NotifyUser("Retrieving all credentials since resource or username are not specified.", NotifyType.StatusMessage);
                    creds = vault.RetrieveAll();
                }

                //If there is only resouce, you can use FindAllByResource() to enumerate by resource.
                //Note: the password will not be returned, you need to call retrieveAll with returned resouce and username to get the credential with password
                else if (InputUserNameValue.Text == "")
                {
                    rootPage.NotifyUser("Retrieve credentials by resouces that you provided", NotifyType.StatusMessage);
                    creds = vault.FindAllByResource(InputResourceValue.Text);
                }

                //If there is only username, you can use findbyusername() to enumerate by resource.
                //Note: the password will not be returned, you need to call retrieveAll with returned resouce and username to get the credential with password
                else if (InputResourceValue.Text == "")
                {
                    rootPage.NotifyUser("Retrieve credentials by username that you provided", NotifyType.StatusMessage);
                    creds = vault.FindAllByUserName(InputUserNameValue.Text);
                }

                //Read by explicit resource and username name, result will be a single credential if it exists. Password will be returned.
                else
                {
                    cred = vault.Retrieve(InputResourceValue.Text, InputUserNameValue.Text);
                }

                //Output credential added to debug spew
                if (creds != null)
                {
                    rootPage.NotifyUser("There are " + creds.Count + " credential(s) found.", NotifyType.StatusMessage);
                    foreach (PasswordCredential c in creds)
                    {
                        try
                        {
                            PasswordCredential c1 = vault.Retrieve(c.Resource.ToString(), c.UserName.ToString());
                            rootPage.NotifyUser("Credential read successfully. " + "Resource: " + c.Resource.ToString() + ", " + "Username: "******"Password: "******".", NotifyType.StatusMessage);
                        }
                        catch (Exception Error)
                        {
                            rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage);
                        }
                    }
                }

                else if (cred != null)
                {
                    rootPage.NotifyUser("Credential read successfully. " + "Resource: " + cred.Resource + ", " + "Username: "******"Password: "******".", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("Credential not found.", NotifyType.StatusMessage);
                }
            }
            catch (Exception Error)
            {
                if (Error.HResult == -2147023728)
                {
                    rootPage.NotifyUser("Credential not found.", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage);
                }
            }
        }
Ejemplo n.º 37
0
        public async Task<TunesUser> SignInUser(string userName, string password, bool useSecureLogin)
        {
            TunesUser tunesUser = null;
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                var client = this.GetHttpClient(useSecureLogin);
                try
                {
                    this.TokenResponse = await client.RequestResourceOwnerPasswordAsync(userName, password);
                    if (this.TokenResponse != null)
                    {
                        if (this.TokenResponse.IsError)
                        {
                            throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage);
                        }

                        Windows.Storage.ApplicationData.Current.RoamingSettings.Values["username"] = userName;
                        Windows.Storage.ApplicationData.Current.RoamingSettings.Values["usesecurelogin"] = useSecureLogin;

                        Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
                        PasswordCredential passwordCredential = new PasswordCredential(PasswordVaultResourceName, userName, password);
                        vault.Add(passwordCredential);

                        if (passwordCredential != null)
                        {
                            tunesUser = this.User = new TunesUser
                            {
                                UserName = userName,
                                Password = vault.Retrieve(PasswordVaultResourceName, passwordCredential.UserName).Password,
                                UseSecureLogin = useSecureLogin
                            };
                        }
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage);
                }
                catch (Exception exception)
                {
                    NullReferenceException nullReferenceException = exception as NullReferenceException;
                    if (nullReferenceException != null)
                    {
                        //there could be a nullreference exception at account change when the login is encrypted.
                        throw new UnauthorizedAccessException(this.m_strEncryptedLoginException);
                    }
                    throw exception;
                }
            }
            else
            {
                throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage);
            }
            return tunesUser;
        }
Ejemplo n.º 38
0
        private void SettingsCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            SettingsCommand channels_cmd = new SettingsCommand("Channels", "Channels", (x) =>
            {
                ShowChannelsView();
            });
            args.Request.ApplicationCommands.Add(channels_cmd);

            SettingsCommand epg_cmd = new SettingsCommand("Epg", "EPG", (x) =>
            {
                ShowEPGView();
            });
            args.Request.ApplicationCommands.Add(epg_cmd);

            SettingsCommand settings_cmd = new SettingsCommand("Settings", "Settings", (x) =>
            {
                ShowSettingsView();
            });
            args.Request.ApplicationCommands.Add(settings_cmd);

            SettingsCommand linc_cmd = new SettingsCommand("Licence", "Privacy Policy", (x) =>
            {
                ShowLicenceView();
            });
            args.Request.ApplicationCommands.Add(linc_cmd);

            SettingsCommand about_cmd = new SettingsCommand("About", "About", (x) =>
            {
                ShowAboutView();
            });
            args.Request.ApplicationCommands.Add(about_cmd);

            SettingsCommand logout_cmd = new SettingsCommand("logout", "Log out", (x) =>
            {
                var vault = new PasswordVault();
                vault.Remove(vault.Retrieve("Sovok.tv WinApp", App.ViewModel.UserAccount.login));
                bool nav = Frame.Navigate(typeof(Login));
                App.ViewModel = new Model.MainViewModel();
            });
        }
Ejemplo n.º 39
-1
 public async Task<TunesUser> VerifyUserCredentials()
 {
     TunesUser tunesUser = null;
     Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
     try
     {
         await Task.Run(() =>
         {
             var userName = (string)Windows.Storage.ApplicationData.Current.RoamingSettings.Values["username"];
             if (!string.IsNullOrEmpty(userName))
             {
                 var passwordCredential = vault.Retrieve(PasswordVaultResourceName, userName);
                 if (passwordCredential != null)
                 {
                     tunesUser = this.User = new TunesUser
                     {
                         UserName = userName,
                         Password = vault.Retrieve(PasswordVaultResourceName, passwordCredential.UserName).Password
                     };
                 }
             }
         });
     }
     catch { }
     return tunesUser;
 }