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 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; }
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 ChangeUser_Click(object sender, RoutedEventArgs e) { try { 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()); } } } catch (Exception Error) // No stored credentials, so none to delete { DebugPrint(Error.ToString()); } Reset1(); Page outputFrame = (Page)rootPage.OutputFrame.Content; Page inputFrame = (Page)rootPage.InputFrame.Content; 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"; }
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); } }
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; }
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 ""; } }
// 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; }
/// <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 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 }
private async System.Threading.Tasks.Task AuthenticateAsync(String provider) { string message; // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; while (credential == null) { try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); } catch (Exception) { // When there is no matching resource an error occurs, which we ignore. } 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<TrainingItem>().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; continue; } } } 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) { message = "You must log in. Login Required"; } } message = string.Format("You are now logged in - {0}", _user.UserId); var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); } }
public PasswordCredential Load() { try { PasswordVault vault2 = new PasswordVault(); return vault2.FindAllByResource(AppResourceName).FirstOrDefault(); } catch (Exception) { return null; } }
public static PasswordCredential getCredential(string resource) { PasswordCredential credential = null; var vault = new PasswordVault(); var credentialList = vault.FindAllByResource(resource); if (credentialList.Count == 1) { credentialList[0].RetrievePassword(); credential = credentialList[0]; } return credential; }
public static void RemoveCredentials() { var vault = new PasswordVault(); try { var credentialList = vault.FindAllByResource(resourceName); foreach (var credential in credentialList) vault.Remove(credential); ServiceUser = null; } catch { } }
public static IReadOnlyList<PasswordCredential> RetrieveAllCredential() { try { PasswordVault vault = new PasswordVault(); return vault.FindAllByResource(CredentialSource); } catch { return null; } }
public void DeleteSavedCredentials() { try { var passwordVault = new PasswordVault(); var credentials = passwordVault.FindAllByResource(PasswordVaultResourceName); if (credentials != null && credentials.Any()) { passwordVault.Remove(credentials[0]); } } catch (Exception) { } }
public static PasswordCredential GetCredentialFromLocker() { PasswordCredential credential = null; var vault = new PasswordVault(); var credentialList = vault.FindAllByResource(resourceName); if (credentialList.Count > 0) { credential = credentialList[0]; } ServiceUser.Name = credential.UserName; return credential; }
// Define a method that performs the authentication process // using a Twitter sign-in. private async Task<bool> AuthenticateAsync() { string message; bool success = false; // This sample uses the Facebook provider. var provider = "Twitter"; // 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) { // When there is no matching resource an error occurs, which we ignore. } 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; // Consider adding a check to determine if the token is // expired, as shown in this post: http://aka.ms/jww5vp. success = true; message = string.Format("Cached credentials for user - {0}", user.UserId); } 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); success = true; } catch (MobileServiceInvalidOperationException) { message = "You must log in. Login Required"; } } return success; }
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()); } }
public static bool IsStored() { var vault = new PasswordVault(); try { IReadOnlyList<PasswordCredential> creds = vault.FindAllByResource("redditAuth"); return creds != null && creds.Count > 0; } catch (Exception) { // The password vault is midly retarded. How is this good default behavior? return false; } }
public static string GetPassword() { var vault = new PasswordVault(); var creds = vault.FindAllByResource("redditAuth"); if (creds != null && creds.Count > 0) { creds[0].RetrievePassword(); return creds[0].Password; } else { return null; } }
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; }
public bool CredentialExists(string app, string userName) { var vault = new PasswordVault(); try { var credential = vault.FindAllByResource(app).FirstOrDefault(c => c.UserName == userName); return credential != null; } catch (Exception) { // If no credentials have been stored with the given name, an exception is thrown. } return false; }
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; } }
private void Clear() { try { PasswordVault vault = new PasswordVault(); var items = vault.FindAllByResource(AppResourceName); foreach (var item in items) { vault.Remove(item); } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } }
/// <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 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; }
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"); }
public static bool HasCredentials() { var vault = new PasswordVault(); try { var credentialList = vault.FindAllByResource(resourceName); if (credentialList.Count > 0) { return true; } return false; } catch { return false; } }
/// <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 } }
public static void Clear() { var vault = new PasswordVault(); try { IReadOnlyList<PasswordCredential> creds = vault.FindAllByResource("redditAuth"); if (creds == null) return; foreach (var cred in creds) { vault.Remove(cred); } } catch (Exception) { // The password vault is mildly retarded. } }
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...) } }
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 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); }