Whether it is ASP.NET, Web Service is also a Window Service, only partial permissions of the local computer are sometimes required, and sometimes more permissions, such as reading and writing files on a single server or domain, etc. It takes more permissions, such as domain account privileges. By getting different IMPERSONATIONCONTEXT objects, you can simulate different users to log in. Please see the public static windowsimpersonationContext ImpersonateUser I have generated NetworkSecurity Class (String StrDomain, String Strlogin, String StrPwd,
Logontype logontype,
LogonProvider LogonProvider;
Attached to NetWorkSecurity.cs Source code as follows: / * * Author: tongwei * Date: 2005-1-25 * Rights: China NetWave Inc. @ 2005 * /
Using system; using system.security.principal; using system.security.permissions;
namespace CNW.OMP.Common.Utility {public enum LogonType: int {/// /// This logon type is intended for users who will be interactively using the computer, such as a user /// being logged on by a terminal server, remote shell, or similar process. This logon type has the /// additional expense of caching logon information for disconnected operation, and is therefore /// inappropriate for some client / server applications, such as a mail server. / // summary> LOGON32_LOGON_INTERACTIVE = 2, /// /// This logon type is intended for high performance servers to authenticate clear text passwords. /// The LogonUser function does not cache credentials for this logon type. / // summary> Logon32_logon_network = 3,
/// /// This logon type is intended for batch servers, where processes may be executing on behalf of a user /// without their direct intervention; or for higher performance servers that process many clear-text /// authentication attempts at a time, such as mail or web servers. The LogonUser function does not cache /// credentials for this logon type. /// summary> LOGON32_LOGON_BATCH = 4, /// /// Indicates a service-type logon. The account provided must have the service privilege enabled. /// summary> LOGON32_LOGON_SERVICE = 5, /// /// This logon type is intended for GINA DLLs logging on users who will be interactively Using the computer. /// this logon type allows a unique audit record to be generated That Shows when the workstation tas unlocked. /// summary> Logon32_logon_unlock = 7,
/// /// Windows XP / 2000: This logon type preserves the name and password in the authentication packages, /// allowing the server to make connections to other network servers while impersonating the client /// This allows. a server to accept clear text credentials from a client, call LogonUser, verify that /// the user can access the system across the network, and still communicate with other servers. /// summary> LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
/// /// Windows XP / 2000: This logon type allows the caller to clone its current token and specify new credentials /// for outbound connections The new logon session has the same local identity, but uses different credentials. /// for other network connections /// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider /// summary> LOGON32_LOGON_NEW_CREDENTIALS = 9}; public enum LogonProvider:.. int {/// /// . Use the standard logon provider for the system The default security provider is NTLM /// Windows XP:. The default provider is negotiate, unless you pass NULL for the domain name and /// the user name is not in UPN format in. This Case The Default Provider is NTLM. /// summary> logon32_provider_default = 0,
/// /// use the windows NT 3.5 logon provider. /// summary> logon32_provider_winnt35 = 1,
/// /// use the ntlm logon provider. /// summary> logon32_provider_winnt40 = 2,
/// /// windows XP / 2000: use the negotiate logon provider. /// summary> logon32_provider_winnt50 = 3};
class SecuUtil32 {[DllImport ( "advapi32.dll", SetLastError = true)] public static extern bool LogonUser (String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle);
[DLLIMPORT ("kernel32.dll", charset = charset.auto)] public extern static bool closehandle (INTPTR HANDLE);
[DllImport ( "advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateToken (IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);} public class NetworkSecurity {public NetworkSecurity () {// / / TODO: Add Constructor Logic Here //}
/// /// The ImpersonateUser function attempts to log a user on to the local computer. /// The local computer is the computer from which ImpersonateUser was called. /// You can not use ImpersonateUser to log on to a remote computer. /// you specify the user with a user name and domain, and authenticate the user with a clear-text password. /// If the function succeeds, you receive a handle to a token that represents the logged-on user . /// in summary> /// /// specifies the name of the domain or server whose account database contacts the strogin account. /// param> /// specifies the name of the user. parame = "strpwd"> Specifies The Clear-text Password for the user account specified by strlogin. param> /// Specifi Es The Type of Logon Operation To Perform. param> ///
NetworkSecurity.ImpersonateUser (strDomain, strUser, strPassword, /// LogonType.LOGON32_LOGON_SERVICE, /// LogonProvider.LOGON32_PROVIDER_DEFAULT); ///} /// catch /// {/// ///} /// /// // Work under this logined user /// // iPContext.undo (); /// example> /// /// // /// // /// ///////////// /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////> string strPwd, LogonType logonType, logonProvider logonProvider) {// Initialize tokens IntPtr tokenHandle = new IntPtr (0); IntPtr dupeTokenHandle = new IntPtr (0); tokenHandle = IntPtr.Zero; dupeTokenHandle = IntPtr.Zero; // If domain name was Blank, Assume Local Machine IF (strdomain == ") strdomain = system.environment.machinename; try {const Int securityimpersonation = 2;
// Call Logonuser to Obtain A Handle To An Access Token. Bool ReturnValue = Secuutil32.logonuser (Strlogin, Strdomain, Strpwd, (int) logontype, (int) LogonProvider, ref tokenhandle;
? // Did impersonation fail if (false == returnValue) {int ret = Marshal.GetLastWin32Error (); // Throw the exception show the reason why LogonUser failed string strErr = String.Format ( "LogonUser failed with error code: {0 } ", ret); throw new ApplicationException (strErr, null);} // Get identity before impersonation bool retVal = SecuUtil32.DuplicateToken (tokenHandle, SecurityImpersonation, ref dupeTokenHandle);? // Did DuplicateToken fail if (false == retVal) {// Close existing handle SecuUtil32.CloseHandle (tokenHandle); // Throw the exception show the reason why DuplicateToken failed throw new ApplicationException ( "failed to duplicate token", null);} // Create new identity using new primary token // The token that is passed to the following constructor must // be a primary token in order to use it for impersonation WindowsIdentity newId = new WindowsIdentity (dupeTokenHandle);. WindowsImpersonationContext Impersonateduser = newid.impersonate ();
return impersonatedUser;} catch (Exception ex) {throw new ApplicationException (ex.Message, ex);} finally {// Close handle if (tokenHandle = IntPtr.Zero!) SecuUtil32.CloseHandle (tokenHandle); if (dupeTokenHandle = IntPtr! . Zero) secuutil32.closehandle (dupetokenhandle);}}}}
Whether it is ASP.NET, Web Service is also a Window Service, only partial permissions of the local computer are sometimes required, and sometimes more permissions, such as reading and writing files on a single server or domain, etc. It takes more permissions, such as domain account privileges. By obtaining different identities WindowsImpersonationContext object that can simulate different user login, I see public static generated NetworkSecurity class WindowsImpersonationContext ImpersonateUser (string strDomain, string strLogin, string strPwd, LogonType logonType,
LogonProvider LogonProvider;
Attached to NetWorkSecurity.cs Source code as follows: / * * Author: tongwei * Date: 2005-1-25 * Rights: China NetWave Inc. @ 2005 * /
Using system; using system.security.principal; using system.security.permissions;
namespace CNW.OMP.Common.Utility {public enum LogonType: int {/// /// This logon type is intended for users who will be interactively using the computer, such as a user /// being logged on by a terminal server, remote shell, or similar process. This logon type has the /// additional expense of caching logon information for disconnected operation, and is therefore /// inappropriate for some client / server applications, such as a mail server. / // summary> LOGON32_LOGON_INTERACTIVE = 2, /// /// This logon type is intended for high performance servers to authenticate clear text passwords. /// The LogonUser function does not cache credentials for this logon type. / // summary> Logon32_logon_network = 3,
/// /// This logon type is intended for batch servers, where processes may be executing on behalf of a user /// without their direct intervention; or for higher performance servers that process many clear-text /// authentication attempts at a time, such as mail or web servers. The LogonUser function does not cache /// credentials for this logon type. /// summary> LOGON32_LOGON_BATCH = 4, /// /// Indicates a service-type logon. The account provided must have the service privilege enabled. /// summary> LOGON32_LOGON_SERVICE = 5, /// /// This logon type is intended for GINA DLLs logging on users who will be interactively Using the computer. /// this logon type allows a unique audit record to be generated That Shows when the workstation tas unlocked. /// summary> Logon32_logon_unlock = 7,
/// /// Windows XP / 2000: This logon type preserves the name and password in the authentication packages, /// allowing the server to make connections to other network servers while impersonating the client /// This allows. a server to accept clear text credentials from a client, call LogonUser, verify that /// the user can access the system across the network, and still communicate with other servers. /// summary> LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
/// /// Windows XP / 2000: This logon type allows the caller to clone its current token and specify new credentials /// for outbound connections The new logon session has the same local identity, but uses different credentials. /// for other network connections /// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider /// summary> LOGON32_LOGON_NEW_CREDENTIALS = 9}; public enum LogonProvider:.. int {/// /// . Use the standard logon provider for the system The default security provider is NTLM /// Windows XP:. The default provider is negotiate, unless you pass NULL for the domain name and /// the user name is not in UPN format in. This Case The Default Provider is NTLM. /// summary> logon32_provider_default = 0,
/// /// use the windows NT 3.5 logon provider. /// summary> logon32_provider_winnt35 = 1,
/// /// use the ntlm logon provider. /// summary> logon32_provider_winnt40 = 2,
/// /// windows XP / 2000: use the negotiate logon provider. /// summary> logon32_provider_winnt50 = 3};
class SecuUtil32 {[DllImport ( "advapi32.dll", SetLastError = true)] public static extern bool LogonUser (String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle);
[DLLIMPORT ("kernel32.dll", charset = charset.auto)] public extern static bool closehandle (INTPTR HANDLE);
[DllImport ( "advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateToken (IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);} public class NetworkSecurity {public NetworkSecurity () {// / / TODO: Add Constructor Logic Here //}
/// /// The ImpersonateUser function attempts to log a user on to the local computer. /// The local computer is the computer from which ImpersonateUser was called. /// You can not use ImpersonateUser to log on to a remote computer. /// you specify the user with a user name and domain, and authenticate the user with a clear-text password. /// If the function succeeds, you receive a handle to a token that represents the logged-on user . /// in summary> /// /// specifies the name of the domain or server whose account database contacts the strogin account. /// param> /// specifies the name of the user. parame = "strpwd"> Specifies The Clear-text Password for the user account specified by strlogin. param> /// Specifi Es The Type of Logon Operation To Perform. param> ///
NetworkSecurity.ImpersonateUser (strDomain, strUser, strPassword, /// LogonType.LOGON32_LOGON_SERVICE, /// LogonProvider.LOGON32_PROVIDER_DEFAULT); ///} /// catch /// {/// ///} /// /// // Work under this logined user /// // iPContext.undo (); /// example> /// /// // /// // /// ///////////// /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////> string strPwd, LogonType logonType, logonProvider logonProvider) {// Initialize tokens IntPtr tokenHandle = new IntPtr (0); IntPtr dupeTokenHandle = new IntPtr (0); tokenHandle = IntPtr.Zero; dupeTokenHandle = IntPtr.Zero; // If domain name was Blank, Assume Local Machine IF (strdomain == ") strdomain = system.environment.machinename; try {const Int securityimpersonation = 2;
// Call Logonuser to Obtain A Handle To An Access Token. Bool ReturnValue = Secuutil32.logonuser (Strlogin, Strdomain, Strpwd, (int) logontype, (int) LogonProvider, ref tokenhandle;
? // Did impersonation fail if (false == returnValue) {int ret = Marshal.GetLastWin32Error (); // Throw the exception show the reason why LogonUser failed string strErr = String.Format ( "LogonUser failed with error code: {0 } ", ret); throw new ApplicationException (strErr, null);} // Get identity before impersonation bool retVal = SecuUtil32.DuplicateToken (tokenHandle, SecurityImpersonation, ref dupeTokenHandle);? // Did DuplicateToken fail if (false == retVal) {// Close existing handle SecuUtil32.CloseHandle (tokenHandle); // Throw the exception show the reason why DuplicateToken failed throw new ApplicationException ( "failed to duplicate token", null);} // Create new identity using new primary token // The token that is passed to the following constructor must // be a primary token in order to use it for impersonation WindowsIdentity newId = new WindowsIdentity (dupeTokenHandle);. WindowsImpersonationContext Impersonateduser = newid.impersonate ();
return impersonatedUser;} catch (Exception ex) {throw new ApplicationException (ex.Message, ex);} finally {// Close handle if (tokenHandle = IntPtr.Zero!) SecuUtil32.CloseHandle (tokenHandle); if (dupeTokenHandle = IntPtr! . Zero) secuutil32.closehandle (dupetokenhandle);}}}}
Author Blog:
http://blog.9cbs.net/pinping1314/