public void Remove(string key) { var vault = new Windows.Security.Credentials.PasswordVault(); var passwordCredential = vault.Retrieve(Windows.ApplicationModel.Package.Current.Id.Name, key); vault.Remove(passwordCredential); }
private static void _AddOrUpdateAccount(string mailAddress, string password) { var id = mailAddress; if (String.IsNullOrWhiteSpace(mailAddress) || String.IsNullOrWhiteSpace(password)) { throw new Exception(); } var vault = new Windows.Security.Credentials.PasswordVault(); try { var credential = vault.Retrieve(nameof(HohoemaApp), id); vault.Remove(credential); } catch { } { var credential = new Windows.Security.Credentials.PasswordCredential(nameof(HohoemaApp), id, password); vault.Add(credential); } }
private void LoginBtn_Click(object sender, RoutedEventArgs e) { if ((string.IsNullOrEmpty(UsernameTxt.Text) == true) || (string.IsNullOrEmpty(PasswordTxt.Password) == true)) { ErrorTxt.Text = "Enter all the fields!"; } else { bool isValid = UserDB.CheckValidUser(UsernameTxt.Text); if (isValid == true) { var vault = new Windows.Security.Credentials.PasswordVault(); var credential = vault.Retrieve("TaskManagerApp", UsernameTxt.Text); if (credential.Password.Equals(PasswordTxt.Password)) { App.CurrentUser = UsernameTxt.Text; App.localSettings.Values["UserLoggedIn"] = App.CurrentUser; this.Frame.Navigate(typeof(HomePage)); } else { ErrorTxt.Text = "Incorrect Password!"; } } else { ErrorTxt.Text = "User Name does not exist!"; } } }
private static void _AddOrUpdateAccount(string mailAddress, string password) { var id = mailAddress; if (String.IsNullOrWhiteSpace(mailAddress) || String.IsNullOrWhiteSpace(password)) { throw new Models.Infrastructure.HohoemaExpception(); } var vault = new Windows.Security.Credentials.PasswordVault(); try { var credential = vault.Retrieve(AccountResrouceKey, id); vault.Remove(credential); } catch { } { var credential = new Windows.Security.Credentials.PasswordCredential(AccountResrouceKey, id, password); vault.Add(credential); } }
protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args) { var rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Window.Current.Content = rootFrame; Window.Current.Activate(); var op = args.ShareOperation; var credentialVault = new Windows.Security.Credentials.PasswordVault(); var credentialList = credentialVault.RetrieveAll(); if (credentialList.Count > 0) { var credential = credentialVault.Retrieve("Imgur", "AccessToken"); credential.RetrievePassword(); ApiClient.InitializeApiClient(credential.Password); rootFrame.Navigate(typeof(Pages.Upload), op); } else { op.ReportError("Please sign in to Imgur first and try again."); } }
public bool TryGetRecentLoginAccount(out Tuple <string, string> mailAndPassword) { try { var vault = new Windows.Security.Credentials.PasswordVault(); var oldItems = vault.FindAllByResource(nameof(Uncord)); if (oldItems.Count == 0) { mailAndPassword = null; return(false); } var prevAccount = oldItems.First(); var retrievedAccount = vault.Retrieve(prevAccount.Resource, prevAccount.UserName); if (string.IsNullOrWhiteSpace(retrievedAccount.UserName) || string.IsNullOrWhiteSpace(retrievedAccount.Password) ) { mailAndPassword = null; return(false); } mailAndPassword = new Tuple <string, string>(retrievedAccount.UserName, retrievedAccount.Password); return(true); } catch { mailAndPassword = null; return(false); } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; var titleBarCore = CoreApplication.GetCurrentView().TitleBar; titleBarCore.ExtendViewIntoTitleBar = true; var titleBar = ApplicationView.GetForCurrentView().TitleBar; titleBar.ButtonBackgroundColor = Colors.Transparent; titleBar.ButtonInactiveBackgroundColor = Colors.Transparent; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (args.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter var credentialVault = new Windows.Security.Credentials.PasswordVault(); var credentialList = credentialVault.RetrieveAll(); if (credentialList.Count > 0) { var credential = credentialVault.Retrieve("Imgur", "AccessToken"); credential.RetrievePassword(); ApiClient.InitializeApiClient(credential.Password); (Window.Current.Content as Frame).Navigate(typeof(Pages.MainPage)); } else { rootFrame.Navigate(typeof(Pages.Login), args.Arguments); } } // Ensure the current window is active Window.Current.Activate(); } }
/// <summary> /// 访问Url,获取返回数据 /// </summary> /// <param name="url">Url</param> /// <returns>返回数据</returns> public async Task <string> Request(string url) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.CookieContainer = cc; HttpWebResponse res = (HttpWebResponse)await req.GetResponseAsync(); if (res.StatusCode == HttpStatusCode.BadGateway || res.StatusCode == HttpStatusCode.InternalServerError || res.ContentLength == 0) { var vault = new Windows.Security.Credentials.PasswordVault(); var va = vault.FindAllByResource("LearnTHU"); string userId = vault.FindAllByResource("LearnTHU")[0].UserName; if (userId == "2012345678") { return(""); } string passwd = vault.Retrieve("LearnTHU", userId).Password; LoginResult result; if (url.Contains("learn.cic")) { result = await LoginNew(userId, passwd); } else { result = await Login(userId, passwd); } if (result == LoginResult.Success) { req = (HttpWebRequest)WebRequest.Create(url); req.CookieContainer = cc; res = (HttpWebResponse)await req.GetResponseAsync(); } else { throw new Exception("登录失败"); } } string html; if (res.ContentLength == -1) { html = await ReadAllAsync(res.GetResponseStream()); } else { html = await new StreamReader(res.GetResponseStream()).ReadToEndAsync(); } if (res.Cookies.Count > 0) { cc.Add(new Uri(@"http://" + new Uri(url).Host), res.Cookies); } res.Dispose(); return(html); }
public void SetSecured(string id, string value, string clientId, string service, string sharedGroup) { var vault = new Windows.Security.Credentials.PasswordVault(); try { var pass = vault.Retrieve(ResourceIdentifier, $"{clientId}-{id}-{service}"); if (pass != null) vault.Remove(pass); } catch { } vault.Add(new Windows.Security.Credentials.PasswordCredential(ResourceIdentifier, $"{clientId}-{id}-{service}", value)); }
public string GetSecured(string id, string clientId, string service, string sharedGroup) { var vault = new Windows.Security.Credentials.PasswordVault(); try { return vault.Retrieve(ResourceIdentifier, $"{clientId}-{id}-{service}").Password; } catch { return ""; } }
private void GetHostKeyFromVault() { try { var vault = new Windows.Security.Credentials.PasswordVault(); hostKey = vault.Retrieve(AnkiWebLogin.VAULT_RESOURCE, AnkiWebLogin.VAULT_USERNAME).Password; } catch { throw new PasswordVaulException("No hostkeys!"); } }
public string Unprotect(string key) { try { var vault = new Windows.Security.Credentials.PasswordVault(); return(vault.Retrieve(Windows.ApplicationModel.Package.Current.Id.Name, key).Password); } catch { return(null); } }
public void SetSecured(string id, string value, string clientId, string service, string sharedGroup) { var vault = new Windows.Security.Credentials.PasswordVault(); try { var pass = vault.Retrieve(ResourceIdentifier, $"{clientId}-{id}-{service}"); if (pass != null) { vault.Remove(pass); } } catch { } vault.Add(new Windows.Security.Credentials.PasswordCredential(ResourceIdentifier, $"{clientId}-{id}-{service}", value)); }
public void LogOutVk() { var vault = new Windows.Security.Credentials.PasswordVault(); vault.Remove(vault.Retrieve("VkApp", ApplicationService.Instance.Settings.UserId)); this._vkontakte.AccessToken.Token = null; this._vkontakte.AccessToken.UserId = null; ApplicationService.Instance.Settings.AccessToken = null; ApplicationService.Instance.Settings.UserId = null; ApplicationService.Instance.Settings.Save(); Messenger.Default.Send <LoginMessage>(new LoginMessage { Type = LoginType.LogOut, IsSuccess = true }); }
private async void decoClick(object sender, Windows.UI.Xaml.RoutedEventArgs e) { var dialog = new Windows.UI.Popups.MessageDialog( "Voulez-vous vraiment vous déconnecter ? ", "Déconnexion"); dialog.Commands.Add(new Windows.UI.Popups.UICommand("Oui") { Id = 0 }); dialog.Commands.Add(new Windows.UI.Popups.UICommand("Non") { Id = 1 }); dialog.DefaultCommandIndex = 0; dialog.CancelCommandIndex = 1; var result = await dialog.ShowAsync(); if ((Int32)result.Id == 0) { localSettings.Values["token"] = null; localSettings.Values["refresh"] = null; if (!ArelAPI.DataStorage.isTestModeEnabled() && localSettings.Values["stayConnect"] != null) { var vault = new Windows.Security.Credentials.PasswordVault(); string login = API.GetUserLogin(ArelAPI.DataStorage.getData("user")); if (login != "user") //Suppression du password enregistré si il existe { vault.Remove(vault.Retrieve("ARELUWP_User", login)); } localSettings.Values["stayConnect"] = null; } ArelAPI.DataStorage.clearData(); Frame.Navigate(typeof(MainPage)); } }
private Type getProfilePage() { Windows.Security.Credentials.PasswordCredential credential = null; var vault = new Windows.Security.Credentials.PasswordVault(); try { var credentialList = vault.FindAllByResource(AuthViewModel.AUTH_JWT_TOKEN_NS); if (credentialList.Count > 0) { if (credentialList.Count == 1) { credential = credentialList[0]; } else { credential = vault.Retrieve(AuthViewModel.AUTH_JWT_TOKEN_NS, AuthViewModel.AUTH_USERNAME_NS); } } } catch { // do nothing } if (credential == null) { return(typeof(AuthContainer)); } credential.RetrievePassword(); var data = credential.Password; var idAndJWT = data.Split("|"); if (idAndJWT.Length < 2) { return(typeof(AuthContainer)); } int uid = -1; Int32.TryParse(idAndJWT[0], out uid); Config.uid = uid; Config.JWT = idAndJWT[1]; return(typeof(Profile)); }
public static Tuple <string, string> _GetPrimaryAccount() { var vault = new Windows.Security.Credentials.PasswordVault(); try { var primary_id = GetPrimaryAccountId(); if (string.IsNullOrWhiteSpace(primary_id)) { return(null); } var credential = vault.Retrieve(nameof(HohoemaApp), primary_id); credential.RetrievePassword(); return(new Tuple <string, string>(credential.UserName, credential.Password)); } catch { } return(null); }
private string CheckForValidToken() { var vault = new Windows.Security.Credentials.PasswordVault(); try { var cred = vault.Retrieve(IdentityManager.AccessControlNamespace, Name); IsActive = !IsExpired(cred.Password); if (!IsActive) vault.Remove(cred); return cred.Password; } catch { IsActive = false; return string.Empty; } }
private string CheckForValidToken() { var vault = new Windows.Security.Credentials.PasswordVault(); try { var cred = vault.Retrieve(IdentityManager.AccessControlNamespace, Name); IsActive = !IsExpired(cred.Password); if (!IsActive) { vault.Remove(cred); } return(cred.Password); } catch { IsActive = false; return(string.Empty); } }
private static bool _RemoveAccount(string mailAddress) { var id = mailAddress; if (String.IsNullOrWhiteSpace(mailAddress)) { return(false); } var vault = new Windows.Security.Credentials.PasswordVault(); try { var credential = vault.Retrieve(nameof(HohoemaApp), id); vault.Remove(credential); return(true); } catch { } return(false); }
public static async Task <int> login(bool useLocalSettings = true, string username = "", string password = "") { Debug.WriteLine("[login] begin"); //retrieve username and password if (useLocalSettings) { if (DataAccess.credentialAbsent()) { throw new LoginException("没有指定用户名和密码"); } username = DataAccess.getLocalSettings()["username"].ToString(); if (username == "__anonymous") { throw new LoginException("没有指定用户名和密码"); } var vault = new Windows.Security.Credentials.PasswordVault(); password = vault.Retrieve("Tsinghua_Learn_Website", username).Password; } while (occupied) { await 十1s(.1); } occupied = true; //check for last login if ((DateTime.Now - lastLogin).TotalMinutes < LOGIN_TIMEOUT_MINUTES && lastLoginUsername == username) { Debug.WriteLine("[login] reuses recent session"); occupied = false; return(2); } try { string loginResponse; //login to learn.tsinghua.edu.cn loginResponse = await POST( loginUri, $"leixin1=student&userid={username}&userpass={password}"); //check if successful var alertInfoGroup = Regex.Match(loginResponse, @"window.alert\(""(.+)""\);").Groups; if (alertInfoGroup.Count > 1) { throw new LoginException(alertInfoGroup[1].Value.Replace("\\r\\n", "\n")); } if (loginResponse.IndexOf(@"window.location = ""loginteacher_action.jsp"";") == -1) { throw new ParsePageException("login_redirect"); } //get iframe src HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(await GET(courseListUrl)); string iframeSrc; try { iframeSrc = htmlDoc.DocumentNode.Descendants("iframe") /*MAGIC*/.First().Attributes["src"].Value; } catch (Exception) { throw new ParsePageException("find_cic_iframe"); } //login to learn.cic.tsinghua.edu.cn await 十1s(); await GET(iframeSrc); } catch (Exception e) { occupied = false; Debug.WriteLine("[login] unsuccessful"); throw e; } Debug.WriteLine("[login] successful"); lastLogin = DateTime.Now; lastLoginUsername = username; occupied = false; return(0); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.Style = Resources["RootFrameStyle"] as Style; if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } /* SplashScreen splash = args.SplashScreen; * Splash eSplash = new Splash(splash); * splash.Dismissed += TypedEventHandler<SplashScreen, object>(eSplash.onSplashScreenDismissed); */ // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter try { var vault = new Windows.Security.Credentials.PasswordVault(); var creds = vault.FindAllByResource("VkApp").FirstOrDefault(); if (creds != null) { ApplicationService.Instance.Settings.UserId = creds.UserName; ApplicationService.Instance.Settings.AccessToken = vault.Retrieve("VkApp", ApplicationService.Instance.Settings.UserId).Password; //ApplicationService.Instance.Settings.Save(); ViewModelLocator.AuthService.SetLoginInfoVk(); //Messenger.Default.Send<GoHomeMessage>(new GoHomeMessage()); //((LoginViewModel)DataContext).GoProfileCommand.Execute(null); //Messenger.Default.Send<GoHomeMessage>(new GoHomeMessage()); if (!rootFrame.Navigate(typeof(ProfileViewPage), args.Arguments)) { throw new Exception("Failed to create initial page"); } //Frame.Navigate(typeof(ProfileViewPage)); /* Messenger.Default.Send<NavigateToPageMessage>(new NavigateToPageMessage * { * Page = "/ProfileViewPage" * }); */ } } catch (Exception ex) { if (!rootFrame.Navigate(typeof(LoginView), args.Arguments)) { throw new Exception("Failed to create initial page"); } } } // Ensure the current window is active Window.Current.Activate(); }
public async Task <T> IdentifyAsync <T>(AuthenticationProvider provider, ACSProvider ACSProvider = null) where T : Identity, new() { var vault = new Windows.Security.Credentials.PasswordVault(); try { var tok = vault.Retrieve(AccessControlNamespace, provider.ToString()); if (IsExpired(tok.Password)) { vault.Remove(tok); } else { return(new T() { Token = tok.Password, Success = true, Provider = provider }); } } catch (Exception ex) { } string LoginUrl = ""; string BouncerEndUrl = ""; switch (provider) { case AuthenticationProvider.AzureControlService: if (ACSProvider != null) { LoginUrl = ACSProvider.LoginUrl; } else { if (string.IsNullOrEmpty(AccessControlNamespace)) { throw new ArgumentNullException("AccessControlNamespace"); } if (string.IsNullOrEmpty(Realm)) { throw new ArgumentNullException("Realm"); } if (string.IsNullOrEmpty(BouncerReplyUrl)) { throw new ArgumentNullException("BouncerReplyUrl"); } LoginUrl = string.Format(ACS_Login_Feed, AccessControlNamespace, Realm, BouncerReplyUrl); } BouncerEndUrl = BouncerReplyUrl + "end"; break; case AuthenticationProvider.Facebook: LoginUrl = string.Format(Facebook_Login_Feed, Uri.EscapeDataString(FacebookApplicationID), Uri.EscapeDataString(Facebook_LoginSucces)); BouncerEndUrl = Facebook_LoginSucces; break; } return(await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(LoginUrl), new Uri(BouncerEndUrl)).AsTask <WebAuthenticationResult>() .ContinueWith <T>(t => { var response = t.Result; if (!t.IsFaulted && (response.ResponseStatus == WebAuthenticationStatus.Success)) { string token = response.ResponseData; // response.ResponseData.Substring(response.ResponseData.IndexOf('=') + 1); token = token.Replace(BouncerEndUrl, "").Substring(1); //Assume that the url is the BouncerEndUrl + '#' / '?' + claims. if (provider == AuthenticationProvider.Facebook) { var idx = token.IndexOf("&expires_in="); var time = int.Parse(token.Substring(idx + 12)); token = token.Insert(idx, string.Format("&ExpiresOn={0}", (int)DateTime.UtcNow.Add(TimeSpan.FromSeconds(time)).Subtract(Epoch).TotalSeconds)); } if (UsePasswordVault) { var cred = new Windows.Security.Credentials.PasswordCredential(AccessControlNamespace, provider.ToString(), token); new Windows.Security.Credentials.PasswordVault().Add(cred); } return new T() { Token = token, Success = true, Provider = provider }; } else { return new T() { UnSuccessReason = response.ResponseStatus.ToString(), Success = false, Provider = provider } }; })); }