1) Get currently logged in user details:
We can achieve this by using the WindowsIdentity class of System.Security.Principal namespace. This class provides a static method, getCurrent(), which return a object of WindowsIdentity.
2) Validate windows credentials provided by user:(Ask User Name, Domain and Password from user)
This is little complex compared to above as we need to call a windows API using IntropServices. To accomplish this we need to add a extern function declaration, and then call the function. Following code will help you to understand this better.
[System.Runtime.InteropServices.DllImport("advapi32.dll")]
public static extern bool LogonUser(string userName, string domainName, string password, int LogonType, int LogonProvider, ref IntPtr phToken);
public Form1()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
bool issuccess = false;
string username = GetloggedinUserName();
if (username.ToLowerInvariant().Contains(txtUserName.Text.Trim().ToLowerInvariant()) && username.ToLowerInvariant().Contains(txtDomain.Text.Trim().ToLowerInvariant()))
{
issuccess = IsValidateCredentials(txtUserName.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
}
if (issuccess)
MessageBox.Show("Successfuly Login !!!");
else
MessageBox.Show("User Name / Password / Domain is invalid !!!");
}
private string GetloggedinUserName()
{
System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
return currentUser.Name;
}
private bool IsValidateCredentials(string userName, string password, string domain)
{
IntPtr tokenHandler = IntPtr.Zero;
bool isValid = LogonUser(userName, domain, password, 2, 0, ref tokenHandler);
return isValid;
}
You can also download a sample code from below link:
http://code.msdn.microsoft.com/Add-Window-Authentication-833ba913#content
Gracias
Wonderful and really helpful. Thanks
Though one question here, is there anyway we can get the windows password of currently logged-in user?
Thank you so much. We can’t get the windows password.
Thank you for this, I just have one question. When I try to authenticate a user with a blank password it always returns False. Any way to correct that?