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.

public static extern bool LogonUser(String 
	lpszUsername, String lpszDomain, 
	String lpszPassword, int dwLogonType, int 
	dwLogonProvider, out int phToken);

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 provider=LOGON32_PROVIDER_DEFAULT.
	//User token for specified user is returned 
	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");