Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PasswordBox with WPF - MVVM

Tags:

security

mvvm

wpf

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

like image 264
jeremyalan Avatar asked Aug 09 '10 21:08

jeremyalan


2 Answers

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.

like image 121
Wallstreet Programmer Avatar answered Nov 15 '22 05:11

Wallstreet Programmer


it is only an opinion hope it can help you.

  1. I think the idea not tomake Password as DP is it is easily tracked by external software such as SNOOP.
  2. The least dependency on View Model you have, the better your code. it will help you on unit testing and Upgrade or changes (what would you do if in the future you want to use a third party password box?)
  3. Throw away the state "Code Behind is Useless" use it wisely.

Consider this in your code behind:

void loginButton_Clicked(object s, EventArgs e)
{
    myViewModel.Password = txPwdBox.Password;
    myViewModel.Login();
}
like image 32
ktutnik Avatar answered Nov 15 '22 05:11

ktutnik