//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)); } } }
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); } } }
private static void Save() { if (credential != null) { vault.Remove(credential); } credential = new PasswordCredential(); if (!string.IsNullOrEmpty(Username)) { credential.UserName = Username; } else { credential.UserName = "******"; // Default user } if (!string.IsNullOrEmpty(Password)) { credential.Password = Password; } else { credential.Password = "******"; } credential.Resource = ResourceName; vault.Add(credential); }
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); }
/// <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)); }
public void Save(string userName, string password) { Clear(); PasswordVault vault = new PasswordVault(); vault.Add(new PasswordCredential(AppResourceName, userName, password)); }
public static void SaveCredential(string userName, string password) { PasswordVault passwordVault = new PasswordVault(); PasswordCredential passwordCredential = new PasswordCredential(RESOURCE, userName, password); passwordVault.Add(passwordCredential); }
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 = "ПИН-код не должен быть пустым. Введите ПИН-код повторно."; } }
/// <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"; } }
/// <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); } }
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); } } }
// 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); } } }
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 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 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 void SaveLogin(string username, string password) { PasswordCredential pc; var passwordVault = new Windows.Security.Credentials.PasswordVault(); var list = passwordVault.RetrieveAll().Where(i => String.Compare(i.Resource, RESOURCE) == 0); if((pc = list.FirstOrDefault(i => String.Compare(i.UserName, username) == 0)) != null) { passwordVault.Remove(pc); passwordVault.Add(new Windows.Security.Credentials.PasswordCredential(RESOURCE, username, password)); } else if(list.Count() > 0) { foreach(var p in list) { passwordVault.Remove(p); } } passwordVault.Add(new Windows.Security.Credentials.PasswordCredential(RESOURCE, username, 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 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 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())); }
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 static void SetPassword() { PasswordVault passwordVault = new PasswordVault(); var credentials = new PasswordCredential() { UserName = UserNameText, Resource = ResourceText, Password = PasswordGenerator.Next(PasswordLength) }; passwordVault.Add(credentials); }
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 static void SaveCredential(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return; //用于保证只存在一个用户信息 RemoveCredential(); PasswordVault vault = new PasswordVault(); PasswordCredential cred = new PasswordCredential(CredentialSource, username, password); vault.Add(cred); }
public static void StoreToken(string identifier, string accessToken, long ExpiresIn, string tokenType) { var json = new JsonObject(); var expiresAt = DateTime.UtcNow.ToEpochTime() + ExpiresIn; json["access_token"] = JsonValue.CreateStringValue(accessToken); json["expires_in"] = JsonValue.CreateNumberValue(expiresAt); json["token_type"] = JsonValue.CreateStringValue(tokenType); var vault = new PasswordVault(); vault.Add(new PasswordCredential(identifier, "token", json.Stringify())); }
public void SaveIfttt(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); var vault = new PasswordVault(); foreach (var item in vault.RetrieveAll().Where(v => v.Resource == "ifttt")) { vault.Remove(item); } vault.Add(new PasswordCredential("ifttt", "key", key)); }
// 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; }
public AdnOAuthConnector( string baseUrl, string consumerKey, string consumerSecret) { _client = new RestClient(baseUrl); ConsumerKey = consumerKey; ConsumerSecret = consumerSecret; _vault = new PasswordVault(); _vault.Add(new PasswordCredential( "AdnOAuthConnector", "AccessToken", "-")); _vault.Add(new PasswordCredential( "AdnOAuthConnector", "AccessTokenSecret", "-")); }
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 static void SetNotifierCredential(string username, string password) { var vault = new PasswordVault(); var credentials = vault.RetrieveAll(); foreach (var credential in credentials) { if (credential.Resource == "NOTCRED" && credential.UserName == username) { vault.Remove(credential); } } if (password != null) { vault.Add(new PasswordCredential("NOTCRED", username, password)); } }
private bool SaveSettings(string user, string password, string host, string port, Scheme scheme) { var vault = new PasswordVault(); foreach (var pwdCredential in vault.RetrieveAll()) { vault.Remove(pwdCredential); } vault.Add(new PasswordCredential(ResourceName, user, password)); var res = vault.FindAllByUserName(user); ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; localSettings.Values["host"] = host; localSettings.Values["scheme"] = scheme.ToString(); localSettings.Values["port"] = port.ToString(); MainPage.SplunkService = null; return true; }
public async Task<BackendResponse> Login(string username, string password) { PasswordVault vault = new PasswordVault(); vault.Add(new PasswordCredential("creds", username, password)); HttpWebRequest request = PopulateRequest(new Uri("/Token", UriKind.Relative), POST, "application/x-www-form-urlencoded"); Task<Stream> outStream = request.GetRequestStreamAsync(); FormUrlEncodedContent encodedContent = new FormUrlEncodedContent(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("grant_type", "password") }); Task<string> serializedContentTask = encodedContent.ReadAsStringAsync(); using (StreamWriter writer = new StreamWriter(await outStream)) { await writer.WriteAsync(await serializedContentTask); } try { using (StreamReader response = new StreamReader((await request.GetResponseAsync()).GetResponseStream())) { string responseString = response.ReadToEnd(); JObject responseObject = JObject.Parse(responseString); if (responseObject["access_token"] != null) { _authenticationToken = responseObject["access_token"].ToString(); _authenticationTokenType = responseObject["token_type"].ToString(); Username = responseObject["userName"].ToString(); return BackendResponse.Ok; } else { return BackendResponse.Unauthorized; } } } catch (Exception) { return BackendResponse.Unauthorized; } }
public void SaveFifthplay(string username, string password) { if (username == null) throw new ArgumentNullException(nameof(username)); if (password == null) throw new ArgumentNullException(nameof(password)); var vault = new PasswordVault(); foreach (var item in vault.RetrieveAll().Where(v => v.Resource == "fifthplay")) { vault.Remove(item); } vault.Add(new PasswordCredential("fifthplay", username, password)); if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("fifthplay-username")) ApplicationData.Current.LocalSettings.Values.Add("fifthplay-username", username); else ApplicationData.Current.LocalSettings.Values["fifthplay-username"] = username; }
public static async Task<bool> tryLogin(string username, string password){ Boolean success = false; try { Uri uri = new Uri(String.Format(loginURL, username)); HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.AllowUI = false; filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential( uri.ToString(), username, password); var httpClient = new HttpClient(filter); var response = await httpClient.GetAsync(uri); response.EnsureSuccessStatusCode(); var jsonString = response.Content.ToString(); var result = JsonConvert.DeserializeAnonymousType(jsonString, new { personal_info = new PersonalInfo() }); var personalPhotoUrl = String.Format(photoURL, username); var photoHttpResponse = await httpClient.GetAsync(new Uri(personalPhotoUrl)); var repository = new PersonalInfoRespository(); IBuffer buffer = await photoHttpResponse.Content.ReadAsBufferAsync(); String photo = await repository.SavePhotoAsync(buffer, username); result.personal_info.photo = photo; await repository.SaveAsync(result.personal_info); var vault = new PasswordVault(); vault.Add(new PasswordCredential(VAULT_RESOURCE, username, password)); success = true; } catch (Exception e) { Debug.WriteLine(e.StackTrace); } return success; }
private void SaveCredential() { var resource = InputResourceValue.Text; var userName = InputUserNameValue.Text; var password = InputPasswordValue.Password; if (resource == "" || userName == "" || password == "") { rootPage.NotifyUser("All fields are required when saving a credential.", NotifyType.ErrorMessage); } else { // Add a credential to PasswordVault with provided resource, user name, and password. // Replaces any existing credential with the same resource and user name. var vault = new PasswordVault(); var cred = new PasswordCredential(resource, userName, password); vault.Add(cred); rootPage.NotifyUser("Credential saved successfully. Resource: " + cred.Resource + " Username: "******" Password: " + cred.Password, NotifyType.StatusMessage); } }
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 async Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { var passwordVault = new PasswordVault(); PasswordCredential credential = null; var settings = ApplicationData.Current.RoamingSettings; try { await this.MobileService.LoginAsync(provider); credential = new PasswordCredential(provider.ToString(), this.MobileService.User.UserId, this.MobileService.User.MobileServiceAuthenticationToken); passwordVault.Add(credential); settings.Values[LastUsedProvider] = provider.ToString(); this.OnNavigate?.Invoke(Tasks, null); } catch (InvalidOperationException) { await this.OnShowErrorAsync?.Invoke("Authentication failed. Please try again."); } }
public override async void LoginAsync() { 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; 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.InvokeApiAsync("custom", HttpMethod.Get, new Dictionary<string,string>() ); } 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(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory); // 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(); IsLoggedIn = true; } }
public void StorePassword(string resource, string userName, string password) { _passwordVault.Add(new PasswordCredential(resource, userName, password)); }