Home > C#, WinRT > Using PasswordVault to securely store passwords in WinRT

Using PasswordVault to securely store passwords in WinRT

15/01/2013

The best option to save passwords in a Windows Store app is via PasswordVault. It allows to store and retrieve credentials in a very easy and secure manner. Windows automatically encrypts and protects the data from other apps. Moreover, and more interestingly, it roams credentials to other Windows 8 systems, so that they are immediately available on all our PCs and tablets.

Take a look to this code:

//using Windows.Security.Credentials;
private const string RESOURCE_NAME = "MyCredential";

private void SaveCredential(string userName, string password)
{
    var vault = new PasswordVault();
    var credential = new PasswordCredential(RESOURCE_NAME, userName, password);

    // Permanently stores credential in the password vault.
    vault.Add(credential);
}

private void GetCredential()
{
    string userName, password;

    var vault = new PasswordVault();
    try
    {
        var credential = vault.FindAllByResource(RESOURCE_NAME).FirstOrDefault();
        if (credential != null)
        {
            // Retrieves the actual userName and password.
            userName = credential.UserName;
            password = vault.Retrieve(RESOURCE_NAME, userName).Password;
        }
    }
    catch (Exception)
    {
        // If no credentials have been stored with the given RESOURCE_NAME, an exception
        // is thrown.
    }
}

private void RemoveCredential(string userName)
{
    var vault = new PasswordVault();
    try
    {
        // Removes the credential from the password vault.
        vault.Remove(vault.Retrieve(RESOURCE_NAME, userName));
    }
    catch (Exception)
    {
        // If no credentials have been stored with the given RESOURCE_NAME, an exception
        // is thrown.
    }
}

As we can see, saving and retrieving credentials using PasswordVault is straightforward. Note that, in the GetCredential and RemoveCredential method, an exception is thrown if no credentials have been previously stored with the given RESOURCE_NAME. After invoking the SaveCredential method, we can open the Credential Manager from Control Panel and see the saved credential:

The Credential Manager

The Credential Manager

We have said that credentials are protected from other apps. In fact, every credential is associated to the app that saved it, so if another one try to read it, it would obtain an exception saying that no credentials has been found.

Categories: C#, WinRT
%d bloggers like this: