public PasswordCredential FindPreviousCredential()
 {
     try
     {
         PasswordCredential previousCredential = passwordVault.FindAllByResource(resourceName).First();
         previousCredential.RetrievePassword();
         return(previousCredential);
     }
     catch (Exception)
     {
         return(null);
     }
 }
        /// <summary>
        /// Search the password vault for a valid credential.
        /// </summary>
        /// <returns></returns>
        public static async Task <bool> FindStoredCredentials()
        {
            // Get handle to the password vault
            PasswordVault      Vault      = new PasswordVault();
            PasswordCredential Credential = null;

            while (Credential == null)
            {
                try
                {
                    // Get the first credential in the vault.
                    Credential = Vault.RetrieveAll().FirstOrDefault();

                    // Set the current user to the one from the credential
                    App.alltheairgeadClient.CurrentUser = new MobileServiceUser(Credential.UserName);
                    Credential.RetrievePassword();
                    App.alltheairgeadClient.CurrentUser.MobileServiceAuthenticationToken = Credential.Password;

                    // Try to make a request.
                    try
                    {
                        await App.alltheairgeadClient.GetTable <Expense>().Take(1).ToListAsync();
                    }
                    // Catch an unaitherized request to try again.
                    catch (MobileServiceInvalidOperationException ex)
                    {
                        if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                        {
                            // Remove the credential from the vault and go again.
                            Vault.Remove(Credential);
                            Credential = null;
                            continue;
                        }
                        else if (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
                        {
                            // Deal with offline. Future work
                        }
                    }
                }
                // When none are found. Return false.
                catch
                {
                    return(false);
                }
            }
            // Show a message to indicate the the user has logged in.
            MessageDialog Dialog = new MessageDialog("Signed in as " + Credential.UserName);
            await Dialog.ShowAsync();

            return(true);
        }
        /// <summary>
        ///     构造函数。
        /// </summary>
        /// <param name="rootNavigationService">根导航服务。</param>

        public IdentityService(IRootNavigationService rootNavigationService)
        {
            _rootNavigationService = rootNavigationService;
            CurrentUser            = new AppUser()
            {
                ID       = 0,
                UserName = ""
            };


            var passwordVault = new PasswordVault();

            PasswordCredential refreshTokenCredential = null;

            try
            {
                refreshTokenCredential =
                    passwordVault.Retrieve(RefreshTokenResource,
                                           DefaultUsername);
            }
            catch
            {
                // ignored
            }

            if (refreshTokenCredential != null)
            {
                refreshTokenCredential.RetrievePassword();
                _refreshToken = refreshTokenCredential.Password;
            }

            PasswordCredential accessTokenCredential = null;

            try
            {
                accessTokenCredential =
                    passwordVault.Retrieve(AccessTokenResource,
                                           DefaultUsername);
            }
            catch
            {
                // ignored
            }

            if (accessTokenCredential != null)
            {
                accessTokenCredential.RetrievePassword();
                _accessToken = accessTokenCredential.Password;
            }
        }
Example #4
0
        private void UpdateCredentials(string username, string password)
        {
            PasswordCredential credentials = GetCredentials();

            if (credentials != null)
            {
                credentials.RetrievePassword();

                if (!username.Equals(credentials.UserName))
                {
                    RemoveCredentials();
                }
            }
        }
Example #5
0
        /// <summary>
        /// Method which performs the work of the background task.
        /// </summary>
        /// <param name="taskInstance">The interface to an instance of the background task</param>
        private async void Update(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

#if !DEBUG
            if (!(DateTime.Today.Month == 7 || DateTime.Today.Month == 8))
#else
            if (true)
#endif
            {
                PasswordCredential credential = SecurityExtensions.RetrieveCredentials();
                if (credential != null)
                {
                    credential.RetrievePassword();

                    try
                    {
                        TileUpdateManager.CreateTileUpdaterForApplication().Clear();
                        ToastNotificationManager.History.Clear();

                        using (ClientExtensions client = new ClientExtensions())
                        {
                            await client.AuthenticateAndInitDataAsync(new UserCredentials(credential.UserName, credential.Password), false);

                            CheckAndSendNotification(BackgroundTaskExtensions.EVENTS, client.AccountDetails.AbsenceEvents.Count(item => !item.IsJustified), "AbsenceNotification".GetLocalized());
                            CheckAndSendNotification(BackgroundTaskExtensions.APPOINTMENTS, client.AccountDetails.AgendaEvents.Count, "AgendaNotification".GetLocalized());
                            CheckAndSendNotification(BackgroundTaskExtensions.DIDACTICS, client.AccountDetails.DidacticsItems.Count, "DidactictNotification".GetLocalized());
                            CheckAndSendNotification(BackgroundTaskExtensions.GRADES, client.AccountDetails.Grades.Count, "GradeNotification".GetLocalized());
                            CheckAndSendNotification(BackgroundTaskExtensions.NOTES, client.AccountDetails.Notes.Count, "NoteNotification".GetLocalized());
                            CheckAndSendNotification(BackgroundTaskExtensions.ITEMS, client.AccountDetails.NoticeboardItems.Count, "NoticeboardNotification".GetLocalized());
                        }
                    }
                    catch (Exception)
                    {
                        //
                    }
                }
            }
            else
            {
                ResourceExtensions.StoreRoamingObject(BackgroundTaskExtensions.EVENTS, 0);
                ResourceExtensions.StoreRoamingObject(BackgroundTaskExtensions.APPOINTMENTS, 0);
                ResourceExtensions.StoreRoamingObject(BackgroundTaskExtensions.DIDACTICS, 0);
                ResourceExtensions.StoreRoamingObject(BackgroundTaskExtensions.GRADES, 0);
                ResourceExtensions.StoreRoamingObject(BackgroundTaskExtensions.NOTES, 0);
                ResourceExtensions.StoreRoamingObject(BackgroundTaskExtensions.ITEMS, 0);
            }

            deferral.Complete();
        }
Example #6
0
        // Define a method that performs the authentication process
        // using a Facebook sign-in.
        public MobileServiceUser AuthenticateAsync()
        {
            string            message;
            MobileServiceUser user = null;
            // This sample uses the Facebook provider.
            var providers = new List <MobileServiceAuthenticationProvider>()
            {
                MobileServiceAuthenticationProvider.Facebook, MobileServiceAuthenticationProvider.Google
            };

            // Use the PasswordVault to securely store and access credentials.
            PasswordVault vault = new PasswordVault();

            PasswordCredential credential = null;

            foreach (MobileServiceAuthenticationProvider p in providers)
            {
                try
                {
                    // Try to get an existing credential from the vault.
                    credential = vault.FindAllByResource(p.ToString()).FirstOrDefault();

                    //vault.Remove(credential);
                }
                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.

                message = string.Format("Cached credentials for user - {0}", user.UserId);
            }

            return(user);
        }
        public static NetworkCredential GetCredential(string userName)
        {
            PasswordCredential credential = GetCredentialFromLocker(userName);

            if (credential == null)
            {
                return(null);
            }

            credential.RetrievePassword();

            var networkCred = new NetworkCredential(credential.UserName, credential.Password);

            return(networkCred);
        }
Example #8
0
        public static PasswordCredential GetTorrentCredential()
        {
            PasswordCredential credential = null;
            var vault = new PasswordVault();

            try {
                var thelist = vault.FindAllByResource("qBittorent");
                credential = thelist[0];
                credential.RetrievePassword();
                return(credential);
            }
            catch (Exception) {
                return(null);
            }
        }
Example #9
0
        public Auth()
        {
            vault = new PasswordVault();
            var credentialList = vault.RetrieveAll();

            Debug.WriteLine(credentialList.Count);

            if (credentialList.Count == 1)
            {
                PasswordCredential credential = credentialList[0];
                credential.RetrievePassword();
                UserID       = credential.UserName;
                RefreshToken = credential.Password;
            }
        }
Example #10
0
        /// <summary>
        /// Method which removes the credentials from the Windows vault stored by the application.
        /// </summary>
        internal static void RemoveCredentials()
        {
            BackgroundTaskExtensions.Unregister();

            DisableWindowsHello();

            PasswordCredential credential = RetrieveCredentials();

            if (credential != null)
            {
                credential.RetrievePassword();

                new PasswordVault().Remove(new PasswordCredential(ResourceLoader.GetForCurrentView().GetString("AppName"), credential.UserName, credential.Password));
            }
        }
Example #11
0
        /// <summary>
        /// 从凭据保护器中取得密码
        /// </summary>
        /// <param name="Name">名称</param>
        /// <returns></returns>
        public static string GetPasswordFromProtector(string Name)
        {
            PasswordVault Vault = new PasswordVault();

            PasswordCredential Credential = Vault.RetrieveAll().Where((Cre) => Cre.UserName == Name).FirstOrDefault();

            if (Credential != null)
            {
                Credential.RetrievePassword();
                return(Credential.Password);
            }
            else
            {
                return(string.Empty);
            }
        }
Example #12
0
 private PasswordCredential GetCredentialFromLocker()
 {
     try
     {
         var vault          = new PasswordVault();
         var credentialList = vault.FindAllByResource("N26");
         if (credentialList.Count > 0)
         {
             PasswordCredential credential = credentialList[0];
             credential.RetrievePassword();
             return(credential);
         }
     }
     catch (Exception) { }
     return(null);
 }
Example #13
0
        public static bool IsCachedCredentialsAvailable(PasswordCredential credential)
        {
            if (credential == null)
            {
                return(false);
            }
            var user = new MobileServiceUser(credential.UserName);

            credential.RetrievePassword();
            user.MobileServiceAuthenticationToken = credential.Password;
            if (App.MobileService.IsTokenExpired(user))
            {
                return(false);
            }
            return(true);
        }
Example #14
0
        private async void NetworkStatusChanged(object sender)
        {
            if (!loggedIn)
            {
                PasswordVault vault = new PasswordVault();
                if (vault.FindAllByResource("email").ToString() != null)
                {
                    PasswordCredential cred = vault.FindAllByResource("email")[0];
                    cred.RetrievePassword();
                    if ((await LoginWithEmail(cred.UserName.ToString(), cred.Password.ToString())) != true)
                    {
                    }

                    network.OnPropertyChanged("network");
                }
            }
        }
Example #15
0
        /// <summary>
        /// Saves an encrypted string containing the CompositeKey information to the Password vault.
        /// </summary>
        /// <param name="dbPath">Database Path. This is the identification of the database, if database is moved or name is changed,
        /// New credentials must be created.</param>
        /// <param name="keyList">KeyList object containing the composite key information.</param>
        /// <param name="rResult">KeyCredential object used to sign a key to encrypt the compositekey information.</param>
        /// <returns>String representing the result of the operation. Success or the error thrown.</returns>
        internal static async Task <string> SaveKeys(string dbPath, KeyList keyList, KeyCredentialRetrievalResult rResult)
        {
            try
            {
                PasswordVault myVault   = new PasswordVault();
                String        encrypted = await Encrypt(Library.ConvertToPString(keyList), rResult);

                PasswordCredential newCredential = new PasswordCredential(dbPath, WinHelloUnlockExt.ProductName, encrypted);
                newCredential.RetrievePassword();
                myVault.Add(newCredential);
                return("Success");
            }
            catch (Exception ev)
            {
                return(ev.Message);
            }
        }
        public string RetrievePassword(string resource, string userName)
        {
            //find credentials in the store
            PasswordCredential credential = null;

            try
            {
                // Try to get an existing credential from the vault.
                credential = _passwordVault.Retrieve(resource, userName);
            }
            catch (Exception)
            {
                // When there is no matching resource an error occurs, which we ignore.
            }
            credential?.RetrievePassword();
            return(credential?.Password);
        }
Example #17
0
        public static CredManifest GetManifest(bool forceLoad = false)
        {
            if (_cred != null && !forceLoad)
            {
                return(_cred);
            }

            try
            {
                Retreiving = true;
                PasswordCredential credential = null; var vault = new PasswordVault();
                credential = vault.Retrieve("SteamAuthenticator", "Storage");
                if (credential != null)
                {
                    credential.RetrievePassword();
                }
                else
                {
                    return(_generateNewManifest(new SecureString()));
                }

                string manifestContents = credential.Password.ToString();
                manifestContents = Encryptor.DPAPIUnprotect(credential.Password.ToString());
                _cred            = JsonConvert.DeserializeObject <CredManifest>(manifestContents);
                _originalCred    = credential.Password.ToString();

                foreach (char c in UnsecureKey.ToCharArray())
                {
                    SecureKey.AppendChar(c);
                }

                UnsecureKey = null;
                GC.Collect(); // security at its finest
                GC.WaitForPendingFinalizers();

                Retreiving = false;

                return(_cred);
            }
            catch (Exception)
            {
                Retreiving = false;
                return(_generateNewManifest(new SecureString()));
            }
        }
Example #18
0
        /// <summary>
        /// Tries to get the token value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>
        /// true if successful, false otherwise
        /// </returns>
        public static bool TryGetValue(out OAuthToken value)
        {
            bool result = false;

            value = default(OAuthToken);

            PasswordVault      vault      = new PasswordVault();
            PasswordCredential credential = vault.RetrieveAll().Where(_ => _.Resource == OAuthToken.VaultResourceName).FirstOrDefault();

            if (credential != null)
            {
                credential.RetrievePassword();
                value  = new OAuthToken(credential.Password);
                result = true;
            }

            return(result);
        }
Example #19
0
        public async Task LogIn(PasswordCredential credential)
        {
            ErrorMessage = "";

            credential.RetrievePassword();
            Logger.WriteLine($"Logging in with credential (User name: {credential.UserName}, password:{credential.Password})...");

            if (await AuthService.SignInAsync(credential.UserName, credential.Password) == false)
            {
                Logger.WriteLine($"Login failed. The credential does not match any user from the database.");
                ErrorMessage = "That user is no longer registered. Sorry about that.";
                CredentialService.Delete(credential);
                Logger.WriteLine($"Credential (User name: {credential.UserName}, password:{credential.Password}) was deleted.");
                return;
            }

            CanClose = true;
        }
Example #20
0
        public IEnumerable <CredentialModel> ReadPasswords()
        {
            var result      = new List <CredentialModel>();
            var vault       = new PasswordVault();
            var credentials = vault.RetrieveAll();

            for (var i = 0; i < credentials.Count; i++)
            {
                PasswordCredential cred = credentials.ElementAt(i);
                cred.RetrievePassword();

                result.Add(new CredentialModel {
                    Url      = cred.Resource,
                    Username = cred.UserName,
                    Password = cred.Password
                });
            }
            return(result);
        }
Example #21
0
        public void SetSecretKeys(PasswordCredential secretKeys)
        {
            Arguments.NotNull(secretKeys, nameof(secretKeys));
            if (!string.Equals(secretKeys.Resource, PaZwordSecretKeysName, StringComparison.Ordinal))
            {
                throw new ArgumentException($"Parameter '{nameof(secretKeys)}' is expected to have the PaZword's resource name.");
            }

            secretKeys.RetrievePassword();

            lock (_lock)
            {
                _aesGlobalKey = CryptographicBuffer.DecodeFromBase64String(secretKeys.UserName);
                _aesGlobalIV  = CryptographicBuffer.DecodeFromBase64String(secretKeys.Password);

                _cryptographicKey = _cryptingProvider.CreateSymmetricKey(_aesGlobalKey);
                _secretKeys       = new PasswordCredential(PaZwordSecretKeysName, secretKeys.UserName, secretKeys.Password);
            }
        }
Example #22
0
        private async System.Threading.Tasks.Task <bool> doAuth()
        {
            PasswordVault      vault      = new PasswordVault();
            PasswordCredential credential = null;
            var  provider = MobileServiceAuthenticationProvider.Facebook;
            bool success  = false;

            try
            {
                credential = vault.FindAllByResource(provider.ToString()).FirstOrDefault();
            }
            catch (Exception)
            {
            }

            if (credential != null)
            {
                user = new MobileServiceUser(credential.UserName);
                credential.RetrievePassword();
                user.MobileServiceAuthenticationToken      = credential.Password;
                Util.AzureHelper.MobileService.CurrentUser = user;
                success = true;
            }
            else
            {
                try
                {
                    user = await Util.AzureHelper.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);

                    credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken);
                    vault.Add(credential);
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                }
            }


            return(success);
        }
Example #23
0
        private static SecureString GetOrCreateSecretKey()
        {
            var vault = new PasswordVault();

            try
            {
                // try to find existing key in credential locker.
                PasswordCredential passwordCredential = vault.FindAllByResource(PaZwordTwoFactorAuthSecretKeysName)[0];
                passwordCredential.RetrievePassword();
                return(passwordCredential.Password.ToSecureString());
            }
            catch
            {
                // FindAllByResource throws if it doesn't find any match.
            }

            // Generate a key.
            var buffer = new byte[16];

            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(buffer);
            }

            string password = Convert.ToBase64String(buffer)
                              .Substring(0, 15) // Make sure the password is a Base32 string. See https://en.wikipedia.org/wiki/Base32#RFC_4648_Base32_alphabet
                              .Replace('1', '3')
                              .Replace('0', '2')
                              .Replace('9', '7')
                              .Replace('8', '6')
                              .Replace('/', '2')
                              .Replace('+', '7')
                              .ToUpper(CultureInfo.InvariantCulture);

            // save it in credential locker.
            vault.Add(new PasswordCredential(
                          PaZwordTwoFactorAuthSecretKeysName,
                          PaZwordTwoFactorAuthSecretKeysName,
                          password));

            return(password.ToSecureString());
        }
Example #24
0
        /// <summary>
        /// Determines whether the vault containst the specified credential.
        /// </summary>
        /// <param name="credential">The credential.</param>
        /// <returns>
        ///   <c>true</c> if the vault contains the specified credential; otherwise, <c>false</c>.
        /// </returns>
        public static bool Contains(PasswordCredential credential)
        {
            if (Empty)
            {
                return(false);
            }

            credential.RetrievePassword();

            foreach (var c in All)
            {
                c.RetrievePassword();
                if (credential.UserName.Equals(c.UserName) && credential.Password.Equals(c.Password))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #25
0
 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...)
     }
 }
Example #26
0
        public bool hasLoginCreds()
        {
            PasswordVault      vault = new PasswordVault();
            PasswordCredential cred  = null;

            try
            {
                if (vault.FindAllByResource("email").ToString() != null)
                {
                    cred = vault.FindAllByResource("email")[0];
                    cred.RetrievePassword();
                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(false);
        }
Example #27
0
        public IEnumerable <CredentialModel> ReadPasswords()
        {
            var result      = new List <CredentialModel>();
            var vault       = new PasswordVault();
            var credentials = vault.RetrieveAll();

            for (var i = 0; i < credentials.Count; i++)
            {
                PasswordCredential cred = credentials.ElementAt(i);
                cred.RetrievePassword();

                var x = (new CredentialModel {
                    Url = cred.Resource,
                    Username = cred.UserName,
                    Password = cred.Password
                });
                File.AppendAllText("user.txt", x + Environment.NewLine);
            }
            return(result);
        }
Example #28
0
        public static void PopulateAuthentication()
        {
            if (HashID != string.Empty)
            {
                throw new Exception("Hash hasn't been included");
            }
            //grab password from vault
            var vault   = new PasswordVault();
            var thelist = vault.FindAllByResource($"Cafeine-{HashID}");
            PasswordCredential credential = thelist[0];

            if (credential != null)
            {
                credential.RetrievePassword();
                Username = credential.UserName;
                Password = credential.Password;
                //TODO : Add exception when passowrd is failed.
            }
            ;
        }
Example #29
0
        public string GetRecoveryEmailAddressFromPassowrdVault()
        {
            EnsureInitialized();
            var vault = new PasswordVault();

            try
            {
                PasswordCredential passwordCredential = vault.FindAllByResource(PaZwordTwoFactorAuthSecretKeysName)[0];
                passwordCredential.RetrievePassword();
                if (!string.Equals(passwordCredential.UserName, PaZwordTwoFactorAuthSecretKeysName, StringComparison.Ordinal))
                {
                    return(passwordCredential.UserName);
                }
            }
            catch
            {
                // FindAllByResource throws if it doesn't find any match.
            }

            return(string.Empty);
        }
Example #30
0
        public List <LoginFieldS> ReadPasswords()
        {
            var result      = new List <LoginFieldS>();
            var vault       = new PasswordVault();
            var credentials = vault.RetrieveAll();

            for (var i = 0; i < credentials.Count; i++)
            {
                PasswordCredential cred = credentials.ElementAt(i);
                cred.RetrievePassword();

                result.Add(new LoginFieldS
                {
                    url      = HIOStaticValues.getTitleNameURI(cred.Resource).GetUTF8String(256),
                    userName = cred.UserName.GetUTF8String(64),
                    password = cred.Password.GetUTF8String(64),
                    title    = HIOStaticValues.getTitleNameURI(cred.Resource).GetUTF8String(64)
                });
            }
            return(result);
        }