/// <summary>
/// Logins the user.
/// </summary>
/// <param name="sender">Source of this event.</param>
/// <param name="e">Arguments of this event.</param>
private void ButtonLogin_Click(object sender, RoutedEventArgs e)
{
UserInfo userInfo;
WindowsImpersonationContext impersonationContext = null;
ISecurityProvider provider;
try
{
// Determine whether we need to try impersonating the user
userInfo = new UserInfo(TextBoxUserName.Text);
// If the application is unable to access the domain, possibly because the local user
// running the application does not have access to domain objects, it's possible that
// the user logging in does have access to the domain. So we attempt to impersonate the
// user logging in to allow authentication to proceed
if (!userInfo.DomainRespondsForUser && TryImpersonate(userInfo.LoginID, TextBoxPassword.Password, out impersonationContext))
{
try
{
// Working around a known issue - DirectorySearcher will often throw
// an exception the first time it is used after impersonating another
// user so we get that out of the way here
userInfo.Initialize();
}
catch (InitializationException)
{
// Exception is expected so we ignore it
}
}
// Initialize the security provider
provider = SecurityProviderUtility.CreateProvider(TextBoxUserName.Text);
// Attempt to authenticate user
if (provider.Authenticate(TextBoxPassword.Password))
{
// Setup security provider for subsequent uses
SecurityProviderCache.CurrentProvider = provider;
ClearErrorMessage();
ExitSuccess = true;
}
else
{
// Verify their password hasn't expired
if (provider.UserData.IsDefined && provider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
{
// Display password expired message
DisplayErrorMessage(string.Format("Your password has expired. {0} You must change your password to continue.", provider.AuthenticationFailureReason));
m_displayType = DisplayType.ChangePassword;
ManageScreenVisualization();
TextBoxPassword.Password = "";
}
else
{
// Display login failure message
DisplayErrorMessage("The username or password is invalid. " + provider.AuthenticationFailureReason);
if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
TextBoxUserName.Focus();
else
TextBoxPassword.Focus();
}
}
}
catch (Exception ex)
{
DisplayErrorMessage("Login failed: " + ex.Message);
if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
TextBoxUserName.Focus();
else
TextBoxPassword.Focus();
}
finally
{
if ((object)impersonationContext != null)
{
impersonationContext.Undo();
impersonationContext.Dispose();
}
}
}