Thursday, 13 July 2017

Credential locker

The credential locker is a secure place to store user credentials that roams between devices based on application, so if the user needs to provide credentials to access a webservice they can be stored in the credential locker securely and used in subsequent application launches and between devices.

<Page
    x:Class="pc.CredentialockerExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
            <ComboBox x:Name="Resources_ComboBox"
                      SelectionChanged="Resources_ComboBox_SelectionChanged" />
            <TextBox x:Name="Resource_TextBox" PlaceholderText="Resource" />
            <TextBox x:Name="User_TextBox" PlaceholderText="User name" />
            <TextBox x:Name="Pass_TextBox" PlaceholderText="Password" />
            <Button x:Name="Save_Button" Click="Save_Button_Click" Content="Save"/>
        </StackPanel>
    </Grid>
</Page>


above we build a simple UI for collecting credentials and below we store them in the PasswordVault.

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Security.Credentials;
using System.Collections.Generic;

namespace pc.CredentialockerExample
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            InitializeComponent();
            var vault = new PasswordVault();
            var pcList = vault.RetrieveAll();

            foreach (var pc in pcList)
                Resources_ComboBox.Items.Add(pc.Resource);
        }

        void Save_Button_Click(object sender, RoutedEventArgs e)
        {
            var vault = new PasswordVault();
            var resource = Resource_TextBox.Text;
            var user = User_TextBox.Text;
            var pass = Pass_TextBox.Text;
            var credentials = new PasswordCredential(resource, user, pass);

            vault.Add(credentials);
        }

        private void Resources_ComboBox_SelectionChanged(object sender,
                                                    SelectionChangedEventArgs e)
        {
            var cb = sender as ComboBox;
            var vault = new PasswordVault();
            IReadOnlyList<PasswordCredential> pcs =
                vault.FindAllByResource(cb.SelectedValue.ToString());

            Resource_TextBox.Text = pcs[0].Resource;
            User_TextBox.Text = pcs[0].UserName;
            Pass_TextBox.Text = pcs[0].Password;
        }
    }
}


now the password vault is a bit tricky because it's queried by both the resource name and the username. we just assume that the resource is a unique key, but you'd have to write this restriction in yourself, or you could inherit from the passwordvault and create your own version.