Created
April 22, 2015 14:27
-
-
Save Jalalx/d67f83594f024f39259f to your computer and use it in GitHub Desktop.
Secure + MVVM way of using PasswordBox. For more info: http://briannoyes.net/2015/03/04/wpf-using-passwordbox-in-mvvm/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
How use in View? | |
<PasswordBox> | |
<i:Interaction.Behaviors> | |
<local:PasswordBoxBindingBehavior Password="{Binding Password}"/> | |
</i:Interaction.Behaviors> | |
</PasswordBox> | |
How access to orginal string? | |
public bool Login(string username, SecureString password) | |
{ | |
IntPtr passwordBSTR = default(IntPtr); | |
string insecurePassword = ""; | |
try | |
{ | |
passwordBSTR = Marshal.SecureStringToBSTR(password); | |
insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR); | |
} | |
catch | |
{ | |
insecurePassword = ""; | |
} | |
// immediately use insecurePassword (in local variable) value after decrypting it: | |
return MockServiceProxyCall(username, insecurePassword); | |
} | |
NOTE: In associated ViewModel, use SecurePassword type for Password property. | |
*/ | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Runtime.InteropServices; | |
using System.Security; | |
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Data; | |
using System.Windows.Interactivity; | |
namespace System.Windows.Controls | |
{ | |
public class PasswordBoxBindingBehavior : Behavior<PasswordBox> | |
{ | |
protected override void OnAttached() | |
{ | |
AssociatedObject.PasswordChanged += OnPasswordBoxValueChanged; | |
} | |
public SecureString Password | |
{ | |
get { return (SecureString)GetValue(PasswordProperty); } | |
set { SetValue(PasswordProperty, value); } | |
} | |
public static readonly DependencyProperty PasswordProperty = | |
DependencyProperty.Register("Password", typeof(SecureString), typeof(PasswordBoxBindingBehavior), new PropertyMetadata(null)); | |
private void OnPasswordBoxValueChanged(object sender, RoutedEventArgs e) | |
{ | |
var binding = BindingOperations.GetBindingExpression(this, PasswordProperty); | |
if (binding != null) | |
{ | |
PropertyInfo property = binding.DataItem.GetType().GetProperty(binding.ParentBinding.Path.Path); | |
if (property != null) | |
property.SetValue(binding.DataItem, AssociatedObject.SecurePassword, null); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I can not access the PasswordBoxBindingBehavior
I'm using xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
<local:PasswordBoxBindingBehavior Password="{Binding Password}"/> <--------- Error
</i:Interaction.Behaviors>