Hi, I ask you for a problem I can't resolve.
I'm developing a form application in C# and I need to access a web application (IIS) within the intranet and not to insert crediantials manually (I keep them in code).
I tried using both Win32NativeMethods.LogonUser and advapi32.dll's Logon User methods, but they both return false. Why? Username, domain and password I use are profiled on the remote machine, not on my local machine. Might this be the problem?
There are some solutions on the web but they don't work for me.
Could you help me, please?
Following is the code I tried to use (references: http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/#comment-770)
C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.IO;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespaceOpenWebBrowser_authenticated_CS
{
classProgram
{
[STAThread]
staticvoidMain(string[] args)
{
using (new Impersonator("username", "domain", "password"))
{
string siteUrl = "http://myremotewebapplication";
System.Diagnostics.Process.Start(siteUrl);
}
}
}
publicenum LogonType
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8, // Win2K or higher
LOGON32_LOGON_NEW_CREDENTIALS = 9// Win2K or higher
};
publicenum LogonProvider
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3
};
publicenum ImpersonationLevel
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3
}
classWin32NativeMethods
{
[DllImport("advapi32.dll", SetLastError = true)]
publicstaticexternintLogonUser(string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
publicstaticexternintDuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
publicstaticexternboolRevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
publicstaticexternboolCloseHandle(IntPtr handle);
}
////// Allows code to be executed under the security context of a specified user account.//////////// Implements IDispose, so can be used via a using-directive or method calls;/// ...////// var imp = new Impersonator( "myUsername", "myDomainname", "myPassword" );/// imp.UndoImpersonation();////// ...////// var imp = new Impersonator();/// imp.Impersonate("myUsername", "myDomainname", "myPassword");/// imp.UndoImpersonation();////// ...////// using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )/// {/// .../// [code that executes under the new context]/// .../// }////// ...///publicclassImpersonator : IDisposable
{
private WindowsImpersonationContext _wic;
////// Begins impersonation with the given credentials, Logon type and Logon provider.//////Name of the user.///Name of the domain.///The password. ///Type of the logon.///The logon provider. publicImpersonator(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
{
Impersonate(userName, domainName, password, logonType, logonProvider);
}
////// Begins impersonation with the given credentials.//////Name of the user.///Name of the domain.///The password. publicImpersonator(string userName, string domainName, string password)
{
Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
}
////// Initializes a new instance of the class.///publicImpersonator()
{ }
////// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.///publicvoidDispose()
{
UndoImpersonation();
}
////// Impersonates the specified user account.//////Name of the user.///Name of the domain.///The password. publicvoidImpersonate(string userName, string domainName, string password)
{
Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
}
////// Impersonates the specified user account.//////Name of the user.///Name of the domain.///The password. ///Type of the logon.///The logon provider. publicvoidImpersonate(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
{
UndoImpersonation();
IntPtr logonToken = IntPtr.Zero;
IntPtr logonTokenDuplicate = IntPtr.Zero;
try
{
// revert to the application pool identity, saving the identity of the current requestor
_wic = WindowsIdentity.Impersonate(IntPtr.Zero);
// do logon & impersonateif (Win32NativeMethods.LogonUser(userName,
domainName,
password,
(int)logonType,
(int)logonProvider,
ref logonToken) != 0)
{
if (Win32NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0)
{
WindowsIdentity wi = new WindowsIdentity(logonTokenDuplicate);
wi.Impersonate(); // discard the returned identity context (which is the context of the application pool)
}
elsethrownew Win32Exception(Marshal.GetLastWin32Error());
}
elsethrownew Win32Exception(Marshal.GetLastWin32Error());
}
finally
{
if (logonToken != IntPtr.Zero)
Win32NativeMethods.CloseHandle(logonToken);
if (logonTokenDuplicate != IntPtr.Zero)
Win32NativeMethods.CloseHandle(logonTokenDuplicate);
}
}
////// Stops impersonation.///privatevoidUndoImpersonation()
{
// restore saved requestor identityif (_wic != null)
_wic.Undo();
_wic = null;
}
}
}
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Roei BarRank #1,271 · 1.4K reputationPosted Nov 19, 2009, 8:52 AM EST
you need to use WebRequest
here is a sample :
webRequest.Credentials = new NetworkCredential("User", "Pass");
Stream outStream = webRequest.GetRequestStream();webRequest.Method = "POST"; // you can use either "GET/POST"
webRequest.ContentLength = data.Length;
webRequest.KeepAlive = false;
outStream.Write(data, 0, data.Length);
outStream.Close();
try reading on this in this URL:
http://www.west-wind.com/presentations/dotnetWebRequest/dotnetWebRequest.htm
hope this helps
enjoy ;-)