Wpf – Using PasswordBox with WPF – MVVM

mvvmSecuritywpf

I've read several articles about how to use Attached Properties to bind to the value of a PasswordBox in WPF. However, every article also references the .NET documentation which explains why the PasswordBox was not made bindable in the first place.

I do not consider myself a security expert by any means, but I figure that someone at Microsoft knew what they were doing, and I shouldn't be putting forth the effort trying to undo it.

So, instead, I came up with my own solution.

public class LoginViewModel
{
   // other properties here

   public PasswordBox Password
   {
      get { return m_passwordBox; }
   }

   // Executed when the Login button is clicked.
   private void LoginExecute()
   {
      var password = Password.SecurePassword;

      // do more stuff...
   }
}

Then, in my XAML, I just render the PasswordBox by binding the Password field to a ContentPresenter.

So my question is… is there a problem with doing it this way? I realize that I'm sort of breaking the MVVM in a way by letting actual controls appear in my ViewModel, but at least this seems more correct than just un-securing the password field.

If this is, in fact, a problem, has anyone come up with a solution that doesn't involve using Attached Properties and storing the password in the ViewModel?

Thanks!
-J

Best Answer

What is wrong with storing the password in the VM at least while it is needed during login? You are correct that according to MVVM pattern the VM should not have a reference to a control like a PasswordBox.

In the view, add a handler to the PasswordChanged event. In the handler, update a SecureString property in the VM with the SecurePassword of the passwordbox.

Related Topic