.net 模拟登陆研究学习

不管是asp.net、web service还是window service,程序运行的时候只有本地计算机的部分权限,有时候需要更大的权限,比如读写某台服务器或域中的一台计算机上的文件等,这就需要更大的权限,比如域帐户权限。

通过获取不同身份的WindowsImpersonationContext对象,可以模拟不同用户登陆,请看我生成的NetworkSecurity类的
public static WindowsImpersonationContext ImpersonateUser(string strDomain,
string strLogin,

string strPwd,

LogonType logonType,

LogonProvider logonProvider);

附NetworkSecurity.cs源代码如下:

 

  1. /* 
  2. * Author : TongWei 
  3. * Date : 2005-1-25 
  4. * Rights : China Netwave Inc.@2005 
  5. */ 
  6. using System; 
  7. using System.Runtime.InteropServices; 
  8. using System.Security.Principal; 
  9. using System.Security.Permissions; 
  10. namespace CNW.OMP.Common.Utility 
  11. public enum LogonType : int 
  12. /// <summary> 
  13. /// This logon type is intended for users who will be interactively using the computer, such as a user 
  14. /// being logged on by a terminal server, remote shell, or similar process. This logon type has the 
  15. /// additional expense of caching logon information for disconnected operation, and is therefore 
  16. /// inappropriate for some client/server applications, such as a mail server. 
  17. /// </summary> 
  18. LOGON32_LOGON_INTERACTIVE = 2, 
  19. /// <summary> 
  20. /// This logon type is intended for high performance servers to authenticate clear text passwords. 
  21. /// The LogonUser function does not cache credentials for this logon type. 
  22. /// </summary> 
  23. LOGON32_LOGON_NETWORK = 3, 
  24. /// <summary> 
  25. /// This logon type is intended for batch servers, where processes may be executing on behalf of a user 
  26. /// without their direct intervention; or for higher performance servers that process many clear-text 
  27. /// authentication attempts at a time, such as mail or web servers. The LogonUser function does not cache 
  28. /// credentials for this logon type. 
  29. /// </summary> 
  30. LOGON32_LOGON_BATCH = 4, 
  31. /// <summary> 
  32. /// Indicates a service-type logon. The account provided must have the service privilege enabled. 
  33. /// </summary> 
  34. LOGON32_LOGON_SERVICE = 5, 
  35. /// <summary> 
  36. /// This logon type is intended for GINA DLLs logging on users who will be interactively using the computer. 
  37. /// This logon type allows a unique audit record to be generated that shows when the workstation was unlocked. 
  38. /// </summary> 
  39. LOGON32_LOGON_UNLOCK = 7, 
  40. /// <summary> 
  41. /// Windows XP/2000: This logon type preserves the name and password in the authentication packages, 
  42. /// allowing the server to make connections to other network servers while impersonating the client. 
  43. /// This allows a server to accept clear text credentials from a client, call LogonUser, verify that 
  44. /// the user can access the system across the network, and still communicate with other servers. 
  45. /// </summary> 
  46. LOGON32_LOGON_NETWORK_CLEARTEXT = 8, 
  47. /// <summary> 
  48. /// Windows XP/2000: This logon type allows the caller to clone its current token and specify new credentials 
  49. /// for outbound connections. The new logon session has the same local identity, but uses different credentials 
  50. /// for other network connections. 
  51. /// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider. 
  52. /// </summary> 
  53. LOGON32_LOGON_NEW_CREDENTIALS = 9 
  54. }; 
  55. public enum LogonProvider : int 
  56. /// <summary> 
  57. /// Use the standard logon provider for the system. The default security provider is NTLM. 
  58. /// Windows XP: The default provider is negotiate, unless you pass NULL for the domain name and 
  59. /// the user name is not in UPN format. In this case the default provider is NTLM. 
  60. /// </summary> 
  61. LOGON32_PROVIDER_DEFAULT = 0, 
  62. /// <summary> 
  63. /// Use the Windows NT 3.5 logon provider. 
  64. /// </summary> 
  65. LOGON32_PROVIDER_WINNT35 = 1, 
  66. /// <summary> 
  67. /// Use the NTLM logon provider. 
  68. /// </summary> 
  69. LOGON32_PROVIDER_WINNT40 = 2, 
  70. /// <summary> 
  71. /// Windows XP/2000: Use the negotiate logon provider. 
  72. /// </summary> 
  73. LOGON32_PROVIDER_WINNT50 = 3 
  74. }; 
  75. class SecuUtil32 
  76. [DllImport(/"advapi32.dll/", SetLastError=true)] 
  77. public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, 
  78. int dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle); 
  79. [DllImport(/"kernel32.dll/", CharSet=CharSet.Auto)] 
  80. public extern static bool CloseHandle(IntPtr handle); 
  81. [DllImport(/"advapi32.dll/", CharSet=CharSet.Auto, SetLastError=true)] 
  82. public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, 
  83. int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); 
  84. public class NetworkSecurity 
  85. public NetworkSecurity() 
  86. // 
  87. // TODO: Add constructor logic here 
  88. // 
  89. /// <summary> 
  90. /// The ImpersonateUser function attempts to log a user on to the local computer.  
  91. /// The local computer is the computer from which ImpersonateUser was called. 
  92. /// You cannot use ImpersonateUser to log on to a remote computer. 
  93. /// You specify the user with a user name and domain, and authenticate the user with a clear-text password. 
  94. /// If the function succeeds, you receive a handle to a token that represents the logged-on user. 
  95. /// You can then use this token handle to impersonate the specified user, or in most cases, 
  96. /// to create a process running in the context of the specified user. 
  97. /// </summary> 
  98. /// <param name=/"strDomain/"> 
  99. /// specifies the name of the domain or server whose account database contains the strLogin account. 
  100. /// </param> 
  101. /// <param name=/"strLogin/">specifies the name of the user.</param> 
  102. /// <param name=/"strPwd/">specifies the clear-text password for the user account specified by strLogin.</param> 
  103. /// <param name=/"logonType/">Specifies the type of logon operation to perform.</param> 
  104. /// <param name=/"logonProvider/">Specifies the logon provider.</param> 
  105. /// <example> 
  106. /// //Add System.Security.dll 
  107. /// //using System.Security.Principal; 
  108. /// 
  109. /// string strDomain=ConfigurationSettings.AppSettings[/"mSALoginDomainName/"]; 
  110. /// string strUser=ConfigurationSettings.AppSettings[/"mSALoginDomainUser/"]; 
  111. /// string strPassword=ConfigurationSettings.AppSettings[/"mSALoginDomainPassword/"]; 
  112. /// 
  113. /// WindowsImpersonationContext impContext = null; 
  114. /// try 
  115. /// { 
  116. /// impContext = NetworkSecurity.ImpersonateUser(strDomain,strUser,strPassword, 
  117. /// LogonType.LOGON32_LOGON_SERVICE, 
  118. /// LogonProvider.LOGON32_PROVIDER_DEFAULT); 
  119. /// } 
  120. /// catch 
  121. /// { 
  122. /// 
  123. /// } 
  124. /// 
  125. /// //work under this logined user 
  126. /// 
  127. /// impContext.Undo(); 
  128. /// </example> 
  129. /// <returns> 
  130. /// </returns> 
  131. public static WindowsImpersonationContext ImpersonateUser(string strDomain, 
  132. string strLogin, 
  133. string strPwd, 
  134. LogonType logonType, 
  135. LogonProvider logonProvider) 
  136. // Initialize tokens 
  137. IntPtr tokenHandle = new IntPtr(0); 
  138. IntPtr dupeTokenHandle = new IntPtr(0); 
  139. tokenHandle = IntPtr.Zero; 
  140. dupeTokenHandle = IntPtr.Zero; 
  141. // If domain name was blank, assume local machine 
  142. if (strDomain == /"/"
  143. strDomain = System.Environment.MachineName; 
  144. try 
  145. const int SecurityImpersonation = 2; 
  146. // Call LogonUser to obtain a handle to an access token. 
  147. bool returnValue = SecuUtil32.LogonUser( 
  148. strLogin, 
  149. strDomain, 
  150. strPwd, 
  151. (int)logonType, 
  152. (int)logonProvider, 
  153. ref tokenHandle); 
  154. // Did impersonation fail? 
  155. if (false == returnValue) 
  156. int ret = Marshal.GetLastWin32Error(); 
  157. // Throw the exception show the reason why LogonUser failed 
  158. string strErr = String.Format(/"LogonUser failed with error code : {0}/", ret); 
  159. throw new ApplicationException(strErr, null); 
  160. // Get identity before impersonation 
  161. bool retVal = SecuUtil32.DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle); 
  162. // Did DuplicateToken fail? 
  163. if (false == retVal) 
  164. // Close existing handle 
  165. SecuUtil32.CloseHandle(tokenHandle); 
  166. // Throw the exception show the reason why DuplicateToken failed 
  167. throw new ApplicationException(/"Failed to duplicate token/"null); 
  168. // Create new identity using new primary token 
  169. // The token that is passed to the following constructor must 
  170. // be a primary token in order to use it for impersonation. 
  171. WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle); 
  172. WindowsImpersonationContext impersonatedUser = newId.Impersonate(); 
  173. return impersonatedUser; 
  174. catch (Exception ex) 
  175. throw new ApplicationException(ex.Message, ex); 
  176. finally 
  177. // Close handle 
  178. if (tokenHandle != IntPtr.Zero) 
  179. SecuUtil32.CloseHandle(tokenHandle); 
  180. if (dupeTokenHandle != IntPtr.Zero) 
  181. SecuUtil32.CloseHandle(dupeTokenHandle); 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值