Thursday, December 28, 2006

Validate Windows Domain Account in C#

In C# we can validate windows domain account using following code snippet.

public class WinAPI{
// Use NTLM security provider to check
public const int LOGON32_PROVIDER_DEFAULT = 0x0;
// To validate the account
public const int LOGON32_LOGON_NETWORK = 0x3;

// API declaration for validating user credentials
[DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
//API to close the credential token
[DllImport("kernel32", EntryPoint="CloseHandle")] public static extern long CloseHandle (long hObject);

int hToken=2;
bool ret = WinAPI.LogonUser(strUserName,strDomain,strPwd, WinAPI.LOGON32_LOGON_NETWORK ,
out hToken);

MessageBox.Show (" Valid Windows domain User ");
WinAPI.CloseHandle (hToken);
MessageBox.Show (" Not an valid Windows domain User ");


We call LogonUser Win32 API to validate the user credentials. The class WinAPI declares the required Win32 API's and the constants used.

LogonUser takes username, password and password as plain text and validates the user name against the domain with the given password, if the user name is correct then it returns a handle to the user token in hToken out parameter which can be used by the user to Impersonate or create process using his account. If this is not used then hToken should be closed using CloseHandle Win32 API.


At 10:44 AM, Blogger rawa said...

thank you very much. the code is really excellant but i have a problem if an user account doesnt have a password then the code retrieve that invalid user although the name and domain of the account is correct.why this happened and what is the solution?
if you know please tell me.
I hope to listen from you soon.
Best Regards

At 10:50 AM, Blogger merawa said...

probelm of empty password.
if the password of an account is null or "" the program return the " Not an valid Windows domain User " message despite of existing of the account in the domain.
how can I solve the problem?
thank you for your helping.

At 1:37 AM, Blogger Pradeep Prem Kamal said...

hi Merawa,
Unfortunately the API doesn't work with empty or null passwords, to handle that scenario you may need to call the GetLastError API to get the error code. If error code returned is 1327 then it means that empty or null password.


At 3:30 AM, Blogger Abiya Carol said...

Great site for these post and i am seeing the most of contents have useful for my Carrier.Thanks to such a useful information.Any information are commands like to share him.

PPC Services in Chennai

At 5:52 AM, Blogger شركة المثالي سوبر للخدمات المنزلية 0550171619 said...

شركة تسليك مجاري بالقطيف


Post a Comment

<< Home