Impersonation works on local machine but not webserver

From: Bjorn Ingebrigtsen (bei@hotmail.com)
Date: 10/15/02


From: "Bjorn Ingebrigtsen" <bei@hotmail.com>
Date: Tue, 15 Oct 2002 13:43:20 -0400


I created a simple test project to access a file on a different server. I
impersonated
an admin account, and was able to open the file. Then i moved my test
project
to the web server, and the LogonUser fails. It will not logon with the admin
account.
Both machines are on the same domain. My machine is running Xp, the
webserver
is 2000 Server. Here's some code:
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
public const int LOGON32_LOGON_NETWORK = 3;
WindowsImpersonationContext impersonationContext;
WindowsIdentity originalUserIdentity;
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
public static extern int LogonUser(string lpszUserName, string
lpszDomain,string lpszPassword,int dwLogonType, int dwLogonProvider,ref
IntPtr phToken);
[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
public extern static int DuplicateToken(IntPtr hToken, int
impersonationLevel, ref IntPtr hNewToken);

if(impersonateValidUser("administrator", "domain", "password")){
string path = @\\nameofserver\dir\data.txt;
string myInputString;
FileStream myFileStream = new
FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read);
myStreamReader = new StreamReader(myFileStream);
myInputString = myStreamReader.ReadLine();
Response.Write(myInputString.ToString());
myFileStream.Close();
myStreamReader.Close();
undoImpersonation();
}
else
{
Response.Write("failed");
}

private bool impersonateValidUser(String userName, String domain, String
password){
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
originalUserIdentity = WindowsIdentity.GetCurrent();
if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if(DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
Response.Write(tempWindowsIdentity.IsAuthenticated.ToString());
if (impersonationContext != null)
    return true;
else
return false;
}
else
return false;
}
else
return false;
}
private void undoImpersonation()
{
impersonationContext.Undo();
originalUserIdentity.Impersonate();
}