Getting password from PasswordBox

Robert Strauch picture Robert Strauch · Nov 22, 2012 · Viewed 10.5k times · Source

I have found several information on this issue here at SO but somehow I'm not really getting it ;-) From what I have read, the password of a PasswordBox cannot be bound to a property due to security reasons, i.e. keeping the plain password in memory.

My model contains this:

private SecureString password;
public SecureString Password {
  get { return password; }
  set { password = value; }
}

Though data binding to a PasswordBox is not supported, Microsoft must have some idea how to get the password from the PasswordBox and use it in a secure way, eh?

What could be an appropriate and relatively easy way to do so?

Answer

Tomtom picture Tomtom · Oct 7, 2014

Therefor I have written a UserControl with a bindable Password-SecureString. The code of this UserControl looks like:

Code-Behind:

public partial class BindablePasswordBox : UserControl
    {
        public static readonly DependencyProperty SecurePasswordProperty = DependencyProperty.Register(
           "SecurePassword", typeof(SecureString), typeof(BindablePasswordBox), new PropertyMetadata(default(SecureString)));

        public SecureString SecurePassword
        {
            get { return (SecureString)GetValue(SecurePasswordProperty); }
            set { SetValue(SecurePasswordProperty, value); }
        }

        public BindablePasswordBox()
        {
            InitializeComponent();
        }

        private void PasswordBox_OnPasswordChanged(object sender, RoutedEventArgs e)
        {
            SecurePassword = ((PasswordBox)sender).SecurePassword;
        }

        private void BindablePasswordBox_OnGotFocus(object sender, RoutedEventArgs e)
        {
            passwordBox.Focus();
        }
    }

XAML:

<UserControl x:Class="Sol.Controls.BindablePasswordBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"
             GotFocus="BindablePasswordBox_OnGotFocus">
    <PasswordBox x:Name="passwordBox" PasswordChanged="PasswordBox_OnPasswordChanged"/>
</UserControl>