public async static void LoadSettings() { //PasswordCredential cred = new PasswordCredential("redditMetro", Settings["UserName"].ToString(), Settings["Password"].ToString()); try { PasswordVault = new PasswordVault(); } catch (Exception) { // wtf is going on here! } var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; var container = localSettings.CreateContainer(CONTAINER_NAME, ApplicationDataCreateDisposition.Always); Settings = container.Values; if (!Settings.ContainsKey("UserName")) Settings.Add("UserName", ""); if (!Settings.ContainsKey("SavePassword")) Settings.Add("SavePassword", false); if (!String.IsNullOrEmpty(Settings["UserName"].ToString()) && (bool)Settings["SavePassword"]) { LoginReddit(); } else { isLoggedIn = false; } }
public void Save(string userName, string password) { Clear(); PasswordVault vault = new PasswordVault(); vault.Add(new PasswordCredential(AppResourceName, userName, password)); }
// Define a method that performs the authentication process // using a Facebook sign-in. //private async System.Threading.Tasks.Task AuthenticateAsync() //{ // while (user == null) // { // string message; // try // { // // Change 'MobileService' to the name of your MobileServiceClient instance. // // Sign-in using Facebook authentication. // user = await App.MobileService // .LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory); // message = // string.Format("You are now signed in - {0}", user.UserId); // } // catch (InvalidOperationException) // { // message = "You must log in. Login Required"; // } // var dialog = new MessageDialog(message); // dialog.Commands.Add(new UICommand("OK")); // await dialog.ShowAsync(); // } //} public override async void LogoutAsync() { App.MobileService.Logout(); string message; // This sample uses the Facebook provider. var provider = "AAD"; // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); vault.Remove(credential); } catch (Exception) { // When there is no matching resource an error occurs, which we ignore. } message = string.Format("You are now logged out!"); var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); IsLoggedIn = false; }
private void Save_Click(object sender, RoutedEventArgs e) { TextBox InputResourceValue = rootPage.FindName("InputResourceValue") as TextBox; TextBox InputUserNameValue = rootPage.FindName("InputUserNameValue") as TextBox; PasswordBox InputPasswordValue = rootPage.FindName("InputPasswordValue") as PasswordBox; String result = ""; if (InputResourceValue.Text == "" || InputUserNameValue.Text == "" || InputPasswordValue.Password == "") { DebugPrint("Inputs are missing. Resource, User name and Password are required"); } else { try { // //Add a credential to PasswordVault by supplying resource, username, and password // Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); PasswordCredential cred = new PasswordCredential(InputResourceValue.Text, InputUserNameValue.Text, InputPasswordValue.Password); vault.Add(cred); // //Output credential added to debug spew // result = "Credential saved successfully. " + "Resource: " + cred.Resource.ToString() + " Username: "******" Password: "******"."; DebugPrint(result.ToString()); } catch (Exception Error) // No stored credentials, so none to delete { DebugPrint(Error.Message); } } }
void ChangeUser_Click(object sender, RoutedEventArgs e) { Page outputFrame = (Page)rootPage.OutputFrame.Content; Page inputFrame = (Page)rootPage.InputFrame.Content; try { Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); IReadOnlyList <PasswordCredential> creds = vault.RetrieveAll(); foreach (PasswordCredential c in creds) { try { vault.Remove(c); } catch (Exception Error) // Stored credential was deleted { DebugPrint(Error.ToString()); } } } catch (Exception Error) // No stored credentials, so none to delete { DebugPrint(Error.ToString()); } Reset1(); CleanCombobox(); CheckBox AuthenticationFailCheck = outputFrame.FindName("AuthenticationFailCheck") as CheckBox; AuthenticationFailCheck.IsChecked = false; TextBox WelcomeMessage = inputFrame.FindName("WelcomeMessage") as TextBox; WelcomeMessage.Text = "User has been changed, please resign in with new credentials, choose save and launch scenario again"; }
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); } } }
//Use your consumerKey and ConsumerSecret private async void ButtonBase_OnClick(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(pinText.Text)) { var msgDialog = new MessageDialog("Please Enter the pin showed below"); await msgDialog.ShowAsync(); } else { var pinCode = pinText.Text.Trim(); var userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(pinCode, authenticationContext); Auth.SetCredentials(userCredentials); var vault = new PasswordVault(); vault.Add(new PasswordCredential("Friend", "TwitterAccessToken", userCredentials.AccessToken)); vault.Add(new PasswordCredential("Friend", "TwitterAccessTokenSecret", userCredentials.AccessTokenSecret)); var localSettings = ApplicationData.Current.LocalSettings; var frame = Window.Current.Content as Frame; if (localSettings.Values.ContainsKey("FirstTimeRunComplete")) { frame?.Navigate(typeof(MainPage)); } else { frame?.Navigate(typeof(FirstTimeTutorial)); } } }
public static bool TryGetToken(string resourceName, out TokenCredential tokenCredential) { var vault = new PasswordVault(); tokenCredential = null; try { var creds = vault.FindAllByResource(resourceName); if (creds != null) { var credential = creds.First(); credential.RetrievePassword(); var json = JsonObject.Parse(credential.Password); tokenCredential = new TokenCredential { AccessToken = json["access_token"].GetString(), TokenType = json["token_type"].GetString(), }; double expiresIn = json["expires_in"].GetNumber(); var dt = ((long)expiresIn).ToDateTimeFromEpoch(); tokenCredential.Expires = dt; return true; } } catch { } return false; }
/// <summary> /// Starts the authentication process. /// </summary> /// <param name="provider">The provider to authenticate with.</param> public async Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { try { var vault = new PasswordVault(); // Login with the identity provider. var user = await AzureAppService.Current .LoginAsync(provider); // Create and store the user credentials. var credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (InvalidOperationException invalidOperationException) { if (invalidOperationException.Message .Contains("Authentication was cancelled by the user.")) { throw new AuthenticationCanceledException("Authentication canceled by user", invalidOperationException); } throw new AuthenticationException("Authentication failed", invalidOperationException); } catch (Exception e) { throw new AuthenticationException("Authentication failed", e); } }
/// <summary> /// Save the given credentials in the os password vault /// </summary> /// <param name="password"></param> private static void StoreDatabasePassword(string databaseName, PasswordParameter password) { var vault = new Windows.Security.Credentials.PasswordVault(); vault.Add( new PasswordCredential(databaseName, PASSWORD_VAULT_USER_NAME, password.Password)); }
private void ButtonSetupPIN_Click(object sender, RoutedEventArgs e) { StatusSetupPIN.Text = ""; if (PasswordBoxNEWPIN1.Password != "" || PasswordBoxNEWPIN2.Password != "") { string PinCrypt1 = MakeCryptSHA512(PasswordBoxNEWPIN1.Password); string PinCrypt2 = MakeCryptSHA512(PasswordBoxNEWPIN2.Password); if (PinCrypt1 == PinCrypt2) { #region ЗАПИСАТЬ ПИН В ХРАНИЛИЩЕ var vault = new Windows.Security.Credentials.PasswordVault(); var credential = new Windows.Security.Credentials.PasswordCredential(resourceName, defaultUserName, PinCrypt2); vault.Add(credential); #endregion StackPanelEnterPIN.Visibility = Windows.UI.Xaml.Visibility.Visible; ButtonEnterPin.Visibility = Windows.UI.Xaml.Visibility.Visible; StackPanelSETUPPIN.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } else { StatusSetupPIN.Text = "Введенные ПИН-коды не совпадают. Попробуйте ещё раз."; } } else { StatusSetupPIN.Text = "ПИН-код не должен быть пустым. Введите ПИН-код повторно."; } }
public static void SaveCredentialToLocker(MobileCredentials mobileCredentials) { // clean up var vault = new PasswordVault(); try { var credentialList = vault.FindAllByResource(ResourceName); foreach (var passwordCredential in credentialList) { vault.Remove(passwordCredential); } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } var credential = new PasswordCredential { Resource = ResourceName, UserName = mobileCredentials.MobileNumber, Password = mobileCredentials.Password }; vault.Add(credential); }
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 = "Неверный ПИН-код. Попробуйте ещё раз."; } }
/// <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"; } }
private void SecureSavePassword(string username, string password) { // 資格情報をCredential Lockerへ保存します var vault = new PasswordVault(); var credential = new PasswordCredential(RESOURCE, username, password); vault.Add(credential); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); PasswordVault vault = new PasswordVault(); try { var credentials = vault.FindAllByResource("creds"); if (credentials.Any()) { var credential = credentials.First(); Username.Text = credential.UserName; credential.RetrievePassword(); Password.Password = credential.Password; Login(null, null); } } catch { // no credentials present, just ignore } if (e.Parameter != null) { Username.Text = e.Parameter.ToString(); } }
public static void SaveCredential(string userName, string password) { PasswordVault passwordVault = new PasswordVault(); PasswordCredential passwordCredential = new PasswordCredential(RESOURCE, userName, password); passwordVault.Add(passwordCredential); }
public async Task<bool> login() { Frame rootFrame = Window.Current.Content as Frame; PasswordVault vault = new PasswordVault(); PasswordCredential cred = null; try { if (vault.FindAllByResource("email").ToString() != null) { cred = vault.FindAllByResource("email")[0]; cred.RetrievePassword(); return await this.LoginWithEmail(cred.UserName.ToString(), cred.Password.ToString()); } } catch (Exception) { } try { if (vault.FindAllByResource("facebook").ToString() != null) { cred = vault.FindAllByResource("facebook")[0]; cred.RetrievePassword(); return await LoginWithFacebook(); } } catch (Exception) { return false; } return false; }
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()); } }
private void Save_Click(object sender, RoutedEventArgs e) { String result = ""; if (InputResourceValue.Text == "" || InputUserNameValue.Text == "" || InputPasswordValue.Password == "") { rootPage.NotifyUser("Inputs are missing. Resource, User name and Password are required", NotifyType.ErrorMessage); } else { try { //Add a credential to PasswordVault by supplying resource, username, and password PasswordVault vault = new PasswordVault(); PasswordCredential cred = new PasswordCredential(InputResourceValue.Text, InputUserNameValue.Text, InputPasswordValue.Password); vault.Add(cred); //Output credential added to debug spew rootPage.NotifyUser("Credential saved successfully. " + "Resource: " + cred.Resource.ToString() + " Username: "******" Password: "******".", NotifyType.StatusMessage); } catch (Exception Error) // No stored credentials, so none to delete { rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage); } } }
public string GetSecretFor(string name) { var vault = new PasswordVault(); try { if (vault.RetrieveAll().Count == 0) { return ""; } var credentialList = vault.FindAllByResource(_key); return credentialList .Where(x => x.UserName == name) .Select(x => { x.RetrievePassword(); return x.Password; }) .FirstOrDefault(); } catch (Exception) { // Exception is thrown if the vault isn't properly initialised return ""; } }
public void CheckPreviousAuthentication() { PasswordCredential credential = null; var settings = ApplicationData.Current.RoamingSettings; var lastUsedProvider = settings.Values[LastUsedProvider] as string; if (lastUsedProvider != null) { try { var passwordVault = new PasswordVault(); // Try to get an existing credential from the vault. credential = passwordVault.FindAllByResource(lastUsedProvider).FirstOrDefault(); } catch (Exception) { // When there is no matching resource an error occurs, which we ignore. } } if (credential != null) { this.MobileService.User = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); this.MobileService.User.MobileServiceAuthenticationToken = credential.Password; this.OnNavigate?.Invoke(Tasks, null); } }
/// <summary> /// Adds a credential to the credential locker. /// </summary> /// <param name="credential">The credential to be added.</param> public static void AddCredential(Credential credential) { if (credential == null || string.IsNullOrEmpty(credential.ServiceUri)) return; var serverInfo = IdentityManager.Current.FindServerInfo(credential.ServiceUri); var host = serverInfo == null ? credential.ServiceUri : serverInfo.ServerUri; string passwordValue = null; // value stored as password in the password locker string userName = null; var oAuthTokenCredential = credential as OAuthTokenCredential; var arcGISTokenCredential = credential as ArcGISTokenCredential; var arcGISNetworkCredential = credential as ArcGISNetworkCredential; if (oAuthTokenCredential != null) { userName = oAuthTokenCredential.UserName; if (!string.IsNullOrEmpty(oAuthTokenCredential.OAuthRefreshToken)) // refreshable OAuth token --> we store it so we'll be able to generate a new token from it passwordValue = OAuthRefreshTokenPrefix + oAuthTokenCredential.OAuthRefreshToken; else if (!string.IsNullOrEmpty(oAuthTokenCredential.Token)) passwordValue = OAuthAccessTokenPrefix + oAuthTokenCredential.Token; } else if (arcGISTokenCredential != null) { userName = arcGISTokenCredential.UserName; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(arcGISTokenCredential.Password)) // Token generated from an username/password --> store the password passwordValue = PasswordPrefix + arcGISTokenCredential.Password; } else if (arcGISNetworkCredential != null) { // networkcredential: store the password if (arcGISNetworkCredential.Credentials != null) { NetworkCredential networkCredential = arcGISNetworkCredential.Credentials.GetCredential(new Uri(host), ""); if (networkCredential != null && !string.IsNullOrEmpty(networkCredential.Password)) { userName = networkCredential.UserName; if (!string.IsNullOrEmpty(networkCredential.Domain)) userName = networkCredential.Domain + "\\" + userName; passwordValue = NetworkCredentialPasswordPrefix + networkCredential.Password; } } } // Store the value in the password locker if (passwordValue != null) { var passwordVault = new PasswordVault(); var resource = ResourcePrefix + host; // remove previous resource stored for the same host try // FindAllByResource throws an exception when no pc are stored { foreach (PasswordCredential pc in passwordVault.FindAllByResource(resource)) passwordVault.Remove(pc); } catch {} passwordVault.Add(new PasswordCredential(resource, userName, passwordValue)); } }
// Log the user in with specified provider (Microsoft Account or Facebook) private async Task AuthenticateAsync() { // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); } catch (Exception) { // do nothing } if (credential != null) { // Create a user from the stored credentials. user = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); user.MobileServiceAuthenticationToken = credential.Password; // Set the user from the stored credentials. App.MobileService.CurrentUser = user; try { // Try to return an item now to determine if the cached credential has expired. await App.MobileService.GetTable<Event>().Take(1).ToListAsync(); } catch (MobileServiceInvalidOperationException ex) { if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { // Remove the credential with the expired token. vault.Remove(credential); credential = null; } } } else { try { // Login with the identity provider. user = await App.MobileService.LoginAsync(provider); // Create and store the user credentials. credential = new PasswordCredential(provider, user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (MobileServiceInvalidOperationException ex) { Debug.WriteLine(ex.StackTrace); } } }
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 }; }
static void WriteCredentials() { //Write to Password vault var vault = new Windows.Security.Credentials.PasswordVault(); vault.Add(new Windows.Security.Credentials.PasswordCredential("My App", "username", "password")); Console.WriteLine("Wrote username and password to UWP Password Vault"); }
public void RemoveAccessCode(string app, string userName) { var credential = GetCredential(app, userName); if (credential != null) { var vault = new PasswordVault(); vault.Remove(credential); } }
public void SaveCredentials(string resource, string userName, string password) { var vault = new PasswordVault(); RemoveAllCredentialsByResource(resource, vault); // Add the new credential var passwordCredential = new PasswordCredential(resource, userName, password); vault.Add(passwordCredential); }
public static void ClearRoamedAccounts() { PasswordVault vault = new PasswordVault(); foreach (var credential in vault.RetrieveAll()) { vault.Remove(credential); } }
public void StorePassword(String password) { try { var passwordVault = new Windows.Security.Credentials.PasswordVault(); passwordVault.Add(new Windows.Security.Credentials.PasswordCredential(RESOURCE, Username, password)); } catch { } }
private static void AddCredentialToLocker() { if (!(string.IsNullOrWhiteSpace(_username) || string.IsNullOrWhiteSpace(_password) || string.IsNullOrWhiteSpace(_serverUrl))) { RemoveCredentials(); var credential = new PasswordCredential(_serverUrl, _username, _password); var vault = new Windows.Security.Credentials.PasswordVault(); vault.Add(credential); } }
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; }
public async Task<User> AuthenticateAsync(string userName, string password, bool useSecureLogin = false) { User user = null; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { var client = this.GetHttpClient(useSecureLogin); try { TokenResponse = await client.RequestResourceOwnerPasswordAsync(userName, password); if (TokenResponse != null) { if (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) { user = new User { UserName = userName, UseSecureLogin = useSecureLogin }; m_settingsService.User = user; } } } 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 user; }
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 void UpdateCredentialsInVault(PasswordCredential passwordCredential) { var vault = new PasswordVault(); var credentials = GetCredentialsFromVault(vault); if (credentials != null) { vault.Remove(credentials); } vault.Add(passwordCredential); }
public static void StoreToken(string identifier, TokenResponse response) { var json = new JsonObject(); json["access_token"] = JsonValue.CreateStringValue(response.AccessToken); json["expires_in"] = JsonValue.CreateNumberValue(response.ExpiresIn); json["token_type"] = JsonValue.CreateStringValue(response.TokenType); var vault = new PasswordVault(); vault.Add(new PasswordCredential(identifier, "token", json.Stringify())); }
static bool InitializePasswordVaultInTheBackground() { // Explicitly place this task on a background thread. Task.Factory.StartNew(() => { // any call to the password vault will load the vault. var vault = new PasswordVault(); vault.RetrieveAll(); }); return true; }
private static void RemoveAllCredentialsByResource(string resource, PasswordVault vault) { try { // Remove the old credentials for this resource var oldCredentials = vault.FindAllByResource(resource); foreach (var oldCredential in oldCredentials) { vault.Remove(oldCredential); } } catch (Exception) { } // FindAllByResource throws Exception if nothing stored for that resource }
/// <summary> /// Clears PasswordVault of any saved password /// </summary> public static void ClearAllSavedPasswords() { try { var vault = new Windows.Security.Credentials.PasswordVault(); foreach (var p in vault.RetrieveAll()) { vault.Remove(p); } } catch (Exception) { } }
async private void save(object sender, RoutedEventArgs e) { var vault = new Windows.Security.Credentials.PasswordVault(); vault.Add(new Windows.Security.Credentials.PasswordCredential(Resource.Text, user.Text, pwd.Password)); var dialog = new MessageDialog("Credentials Saved succesfully"); await dialog.ShowAsync(); Resource.Text = string.Empty; user.Text = string.Empty; pwd.Password = string.Empty; }
public string GetStoredPassword() { try { var passwordValut = new Windows.Security.Credentials.PasswordVault(); var creds = passwordValut.Retrieve(RESOURCE, Username); return(creds.Password); } catch { return(null); } }
private void Launch_Click(object sender, RoutedEventArgs e) { try { Page outputFrame = (Page)rootPage.OutputFrame.Content; Page inputFrame = (Page)rootPage.InputFrame.Content; List <String> itemsource = new List <String>(); List <Object> l = new List <Object>(); Reset1(); CheckBox AuthenticationFailCheck = outputFrame.FindName("AuthenticationFailCheck") as CheckBox; TextBox WelcomeMessage = inputFrame.FindName("WelcomeMessage") as TextBox; ComboBox SelectUser = inputFrame.FindName("SelectUser") as ComboBox; if (AuthenticationFailCheck.IsChecked == true) { WelcomeMessage.Text = "Blocked"; } else { try { Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); IReadOnlyList <PasswordCredential> creds = vault.FindAllByResource("Scenario 2"); foreach (var c in (IEnumerable <PasswordCredential>)creds) { itemsource.Insert(0, c.UserName); } itemsource.Sort(); } catch (Exception Error) // If there are no stored credentials, no list to populate { DebugPrint(Error.ToString()); } itemsource.Insert(0, "Add new user"); itemsource.Insert(0, ""); l.AddRange(itemsource); SelectUser.ItemsSource = l; SelectUser.SelectedIndex = 0; WelcomeMessage.Text = "Scenario is ready, please sign in"; } } catch (Exception Error) { // // Bad Parameter, Machine infor Unavailable errors are to be handled here. // DebugPrint(Error.ToString()); } }
/// <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 }); }
private void ButtonDeletePIN_Click(object sender, RoutedEventArgs e) { var vault = new Windows.Security.Credentials.PasswordVault(); string resourceName = "Mastercond.Documents"; string defaultUserName = "******"; string password = MakeCryptSHA512(EnterPINPasswordBox.Password.ToString()); try { vault.Remove(new Windows.Security.Credentials.PasswordCredential(resourceName, defaultUserName, password)); StatusFile.Text = "ПИН-код успешно удален. При следующем входе в приложение Вы сможете установить новый ПИН."; } catch { StatusFile.Text = "Не удалось выполнить сброс ПИН-кода. Проверьте правильность введенного Вами ПИН-кода."; } }
/// <summary> /// Clears any saved password for the given database /// </summary> /// <param name="databaseName"></param> public static void ClearSavedPasswordForDatabase(string databaseName) { // No need to try to remove any saved password if WIndows Hello is not enabled if (SettingsViewModel.Instance.WindowsHelloEnabled) { try { var vault = new Windows.Security.Credentials.PasswordVault(); foreach (var p in vault.FindAllByResource(databaseName)) { vault.Remove(p); } } catch (Exception) { } } }
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); }
private void Launch_Click(object sender, RoutedEventArgs e) { try { Page outputFrame = (Page)rootPage.OutputFrame.Content; Page inputFrame = (Page)rootPage.InputFrame.Content; Reset1(); CheckBox AuthenticationFailCheck = outputFrame.FindName("AuthenticationFailCheck") as CheckBox; TextBox WelcomeMessage = inputFrame.FindName("WelcomeMessage") as TextBox; if (AuthenticationFailCheck.IsChecked == true) { WelcomeMessage.Text = "Blocked"; } else { PasswordCredential cred = new PasswordCredential(); Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); IReadOnlyList <PasswordCredential> Creds = vault.FindAllByResource("Scenario 1"); foreach (PasswordCredential c in Creds) { try { vault.Remove(c); } catch (Exception Error) // Stored credential was deleted { DebugPrint(Error.ToString()); } } WelcomeMessage.Text = "Scenario is ready, please sign in"; } } catch (Exception Error) { // // Bad Parameter, Machine infor Unavailable errors are to be handled here. // DebugPrint(Error.ToString()); } }
private static void LoadPasswordVault() { // any call to the password vault will load the vault vault = new Windows.Security.Credentials.PasswordVault(); try { IReadOnlyList <PasswordCredential> credentials = vault.FindAllByResource(ResourceName); credential = credentials.FirstOrDefault(); if (string.IsNullOrEmpty(credential.Password)) { credential.RetrievePassword(); } _Password = credential.Password; _Username = credential.UserName; } catch (Exception) { // If the credentials is empty the PasswordVault will throw an unspecific Exception (WEIRD...) } }
void Scenario4Button_Click(object sender, RoutedEventArgs e) { try { Windows.Security.Credentials.PasswordVault v = new Windows.Security.Credentials.PasswordVault(); IReadOnlyList <PasswordCredential> creds = v.RetrieveAll(); DeleteSummary.Text = "Number of credentials deleted: " + creds.Count; foreach (PasswordCredential c in creds) { v.Remove(c); } // GetAll is a snapshot in time, so to reflect the updated vault, get all credentials again creds = v.RetrieveAll(); // The credentials should now be empty } catch (Exception Error) { DebugPrint(Error.ToString()); } }
private void StoreCredentialsInVault() { var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings; var container = roamingSettings.CreateContainer(ConnectionContainerName, Windows.Storage.ApplicationDataCreateDisposition.Always); var connection = new Connection { Host = this.Host, RememberMe = this.StoreCredentials, UseSsl = this.UseSsl, Username = this.UserName }; var jsonStringConnection = JsonConvert.SerializeObject(connection); container.Values.Add(this.Host, jsonStringConnection); var vault = new Windows.Security.Credentials.PasswordVault(); vault.Add(new PasswordCredential(this.Host, UserName, Password)); }
void Signin_Click(object sender, RoutedEventArgs e) { Page outputFrame = (Page)rootPage.OutputFrame.Content; Page inputFrame = (Page)rootPage.InputFrame.Content; TextBox InputResourceValue = outputFrame.FindName("InputResourceValue") as TextBox; TextBox InputUserNameValue = outputFrame.FindName("InputUserNameValue") as TextBox; PasswordBox InputPasswordValue = outputFrame.FindName("InputPasswordValue") as PasswordBox; TextBox WelcomeMessage = inputFrame.FindName("WelcomeMessage") as TextBox; CheckBox SaveCredCheck = outputFrame.FindName("SaveCredCheck") as CheckBox; if (InputUserNameValue.Text == "" || InputPasswordValue.Password == "") { TextBox ErrorMessage = outputFrame.FindName("ErrorMessage") as TextBox; ErrorMessage.Text = "User name and password are not allowed to be empty, Please input user name and password"; } else { try { Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); PasswordCredential c = new PasswordCredential(InputResourceValue.Text, InputUserNameValue.Text, InputPasswordValue.Password); if ((Boolean)SaveCredCheck.IsChecked) { vault.Add(c); } WelcomeMessage.Text = "Welcome to " + c.Resource + ", " + c.UserName; } catch (Exception Error) // No stored credentials, so none to delete { DebugPrint(Error.ToString()); } } Reset1(); CheckBox AuthenticationFailCheck = outputFrame.FindName("AuthenticationFailCheck") as CheckBox; AuthenticationFailCheck.IsChecked = false; }
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; } }
async private void delete(object sender, RoutedEventArgs e) { PasswordVault vault = new PasswordVault(); foreach (var cred in vault.RetrieveAll()) { cred.RetrievePassword(); if (cred.Resource == Resource.Text || cred.UserName == user.Text || cred.Password == pwd.Password) { var vaul = new Windows.Security.Credentials.PasswordVault(); vaul.Remove(new Windows.Security.Credentials.PasswordCredential(cred.Resource, cred.UserName, cred.Password)); var dialog = new MessageDialog("Done!!!!"); await dialog.ShowAsync(); } else { var dialog = new MessageDialog("Credentials Does Not Exist"); await dialog.ShowAsync(); } } }
private void Reset_Click(object sender, RoutedEventArgs e) { try { TextBox InputResourceValue = rootPage.FindName("InputResourceValue") as TextBox; InputResourceValue.Text = ""; TextBox InputUserNameValue = rootPage.FindName("InputUserNameValue") as TextBox; InputUserNameValue.Text = ""; PasswordBox InputPasswordValue = rootPage.FindName("InputPasswordValue") as PasswordBox; InputPasswordValue.Password = ""; TextBox ErrorMessage = rootPage.FindName("ErrorMessage") as TextBox; ErrorMessage.Text = ""; Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); IReadOnlyList <PasswordCredential> creds = vault.RetrieveAll(); foreach (PasswordCredential c in creds) { try { vault.Remove(c); } catch (Exception Error) // Stored credential was deleted { DebugPrint(Error.ToString()); } } DebugPrint("Scenario has been reset. All credentials are removed."); } catch (Exception Error) { // // Bad Parameter, Machine infor Unavailable errors are to be handled here. // DebugPrint(Error.Message); } }
private async void AppBarButton_Click(object sender, RoutedEventArgs e) { var vault = new Windows.Security.Credentials.PasswordVault(); LogInButton.IsEnabled = false; TextBoxUsername.IsEnabled = false; PassBoxLoginPass.IsEnabled = false; CheckBoxRememberMe.IsEnabled = false; TSMainHub.IsEnabled = false; StatusText.Text = ""; theLogin = new LoggingIn(TextBoxUsername.Text, PassBoxLoginPass.Password); theLogin.ConnectAndGetLatest(); if (CheckBoxRememberMe.IsChecked == true) { SaveCredential(TextBoxUsername.Text, PassBoxLoginPass.Password); } else if (CheckBoxRememberMe.IsChecked == false) { RemoveCredential(TextBoxUsername.Text); } for (int i = 0; i < 30; i++) { await Task.Delay(1000); if (theLogin.isConnected) { break; } } if (theLogin.isConnected) { await Task.Delay(2000); (App.Current as App).isFirstLogin = false; (App.Current as App).Email = TextBoxUsername.Text; (App.Current as App).Password = PassBoxLoginPass.Password; if (TSMainHub.IsOn) { this.Frame.Navigate(typeof(AutomatedPage)); } else if (!TSMainHub.IsOn) { this.Frame.Navigate(typeof(MainPage)); } } else { LogInButton.IsEnabled = true; TextBoxUsername.IsEnabled = true; PassBoxLoginPass.IsEnabled = true; CheckBoxRememberMe.IsEnabled = true; TSMainHub.IsEnabled = true; StatusText.Text = "Something Went Wrong and We Couldn't\n Log You In"; } }
void MainPage_AccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs args) { // Callback invoked to request the app for accounts when the accounts flyout is about to be displayed // Get the Deferral object and do some async operation if needed var Deferral = args.GetDeferral(); // do some async operation //Uri uri = new Uri("ms-appx:///Assets/Smalllogo.png"); //StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri); // Add CredLocker Credentials CredentialCommandCredentialDeletedHandler credDeletedHandler = new CredentialCommandCredentialDeletedHandler(CredentialDeletedHandler); Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); IReadOnlyList <PasswordCredential> creds = vault.RetrieveAll(); if (creds.Count == 0) { args.HeaderText = "There is not credential saved by the sample app, please go to Scenario 1 and add some credential, then try again."; } else { args.HeaderText = "Here are the credentials saved by sample app in Scenario 1."; } foreach (PasswordCredential c in creds) { try { CredentialCommand credCommand1 = new CredentialCommand(c, credDeletedHandler); // Deleted is invoked after the system deletes the credential args.CredentialCommands.Add(credCommand1); } catch (Exception Error) // Stored credential was deleted { DebugPrint(Error.ToString()); } } try { // Add Global commands Object commandID = 1; UICommandInvokedHandler appCmdInvokedHandler = new UICommandInvokedHandler(CommandInvokedHandler); // SettingsCommand is an existing WinRT class used in the SettingsPane SettingsCommand command = new SettingsCommand( commandID, "App Specific Command Label...", appCmdInvokedHandler); args.Commands.Add(command); // Add more commands here } catch (Exception Error) // No stored credentials, so none to delete { DebugPrint(Error.Message); } // Complete the Deferral() Deferral.Complete(); }
private static void LoadPasswordVault() { // any call to the password vault will load the vault Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); vault.RetrieveAll(); }
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); } } }
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; }
public VaultCredential Get(string domain) { var vault = new PasswordVault(); var credential = vault.FindAllByResource(domain).FirstOrDefault(); credential.RetrievePassword(); return new VaultCredential(credential.Resource, credential.UserName, credential.Password); }