C#, ASP.NET•Use Window Impersonation in Forms-Authentication-Based ASP.NET Apps

Listing 1. The LogonUser method returns a user token, which you can use as a constructor parameter when creating a WindowsIdentity (the second step of the authentication phase). Call GetLastError to try to determine why the logon failed if it didn't succeed.

[DllImport("advapi32.dll")]
public static extern bool LogonUser(String 
	lpszUsername, String lpszDomain, 
	String lpszPassword, int dwLogonType, int 
	dwLogonProvider, out int phToken);

[DllImport("Kernel32.dll")]
public static extern int GetLastError();	

private void Loginbtn_Click(object sender, 
	System.EventArgs e) {
	int ret=0 ;
	int l_token1;
	bool loggedOn = LogonUser(TextBoxUser.Text, 
		"servername", TextBoxPWD.Text,	 
	//Logon type=LOGON32_LOGON_NETWORK_CLEARTEXT.
	3,	 
	//Logon provider=LOGON32_PROVIDER_DEFAULT.
	0,		
	//User token for specified user is returned 
	//here.
	out l_token1);						
			
	//Call GetLastError to try to determine why 
	//logon failed if it did not succeed.
	if (loggedOn == false)
		ret = GetLastError();
	if (ret != 0) 
		throw new Exception 
			("Invalid Username or Password");