Sunday, September 14, 2008

Use windows authentication for your own application.

This sample is very short and clear, if you wish to authenticate your application user as a windows or domain user then follow the next few steps.

Step1: declare an external function like this.
[DllImport("advapi32.dll", SetLastError = true)]
protected static extern bool LogonUser(string sUsername, string sDomain, string sPassword,
int iLogonType, int iLogonProvider, ref IntPtr ipToken);


Step2: Call the function.
IntPtr pExistingTokenHandle = new IntPtr(0);
pExistingTokenHandle = IntPtr.Zero;
const int LOGON32_PROVIDER_DEFAULT = 0;
// create token
const int LOGON32_LOGON_INTERACTIVE = 2;
string sUserName = "use1";
string sDomain = "domain1";
string sPassword = "Test123";
bool bImpersonated = LogonUser(sUserName, sDomain, sPassword,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);

This "bImpersonated" return True if user authenticated and false if not. And you can decide actions for your application based on this.

No comments: