Check User Authentication Programmatically


Many often it is required to check user authentication programmatically. Suppose you want to create a UI for taking user input of User ID and Password. Based on that UserID and password, Your windows service will run. So when user input userid and password then you must authenticate before store that information.


So far no direct Donet framework(upto 3.5 sp1) component available for check user authentication programmatically. So you need to take help from windows api for that service.

The following code can capable to authenticate both local or domain account.

How Windows API help you

In "advapi32.dll" contain a function name "LogonUser". That function will help you to authenticate user programmatically.

To use that function you need to declare 2 enumaration named "LogonSessionType" and "LogonProvider"

Code Example is given bellow

class Program
static void Main(string[] args)
IntPtr token = new IntPtr();

//First Parameter is User Name, second: domain/machine name, third password
bool result = AuthenticationManager.LogonUser("Administrator", "", "abcd", AuthenticationManager.LogonSessionType.Network, AuthenticationManager.LogonProvider.Default, out token);

if (result)
Console.WriteLine("User ID and Password is correct");
Console.WriteLine("Not real user");


/// Authentication Programmatically

class AuthenticationManager
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(string principal, string authority, string password, LogonSessionType logonType, LogonProvider logonProvider, out IntPtr token);

public enum LogonSessionType : uint
Interactive = 2, Network, Batch, Service, NetworkClearText = 8, NewCredencials

public enum LogonProvider : uint
Default = 0, WinNT35, WinNT40, WinNT50


Note: Microsoft Pattern an Practices have a nice artical related to that. The heading of that artical is

"How To Use Impersonation and Delegation in ASP.NET 2.0"

If you read that then i think many others problem you can solve realted to that issue.

No comments: