.net下模拟不同身份登陆以获取不同权限

 

  1 None.gif .net下模拟不同身份登陆以获取不同权限  
  2 None.gif 
  3 None.gif作者:佚名 时间: 2004 - 04 - 16   09 : 14  出处:互连网 责编:chinaitpower  
  4 None.gif 
  5 None.gif              摘要:.net下模拟不同身份登陆以获取不同权限 
  6 None.gif 
  7 None.gif 
  8 None.gif不管是asp.net、web service还是window service,程序运行的时候只有本地计算机的部分权限,有时候需要更大的权限,比如读写某台服务器或域中的一台计算机上的文件等,这就需要更大的权限,比如域帐户权限。 
  9 None.gif
 10 None.gif通过获取不同身份的WindowsImpersonationContext对象,可以模拟不同用户登陆,请看我生成的NetworkSecurity类的 
 11 None.gif public   static  WindowsImpersonationContext ImpersonateUser( string  strDomain, 
 12 None.gif string  strLogin, 
 13 None.gif
 14 None.gif string  strPwd, 
 15 None.gif
 16 None.gifLogonType logonType, 
 17 None.gif
 18 None.gifLogonProvider logonProvider); 
 19 None.gif
 20 None.gif附NetworkSecurity.cs源代码如下: 
 21 None.gif
 22 ExpandedBlockStart.gifContractedBlock.gif /**/ /* 
 23InBlock.gif* Author : TongWei 
 24InBlock.gif* Date : 2005-1-25 
 25InBlock.gif* Rights : China Netwave Inc.@2005 
 26ExpandedBlockEnd.gif*/
 
 27 None.gif
 28 None.gif using  System; 
 29 None.gif using  System.Runtime.InteropServices; 
 30 None.gif using  System.Security.Principal; 
 31 None.gif using  System.Security.Permissions; 
 32 None.gif
 33 None.gif namespace  CNW.OMP.Common.Utility 
 34 ExpandedBlockStart.gifContractedBlock.gif dot.gif
 35InBlock.gifpublic enum LogonType : int 
 36ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
 37ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 38InBlock.gif/// This logon type is intended for users who will be interactively using the computer, such as a user 
 39InBlock.gif/// being logged on by a terminal server, remote shell, or similar process. This logon type has the 
 40InBlock.gif/// additional expense of caching logon information for disconnected operation, and is therefore 
 41InBlock.gif/// inappropriate for some client/server applications, such as a mail server. 
 42ExpandedSubBlockEnd.gif/// </summary> 

 43InBlock.gifLOGON32_LOGON_INTERACTIVE = 2
 44InBlock.gif
 45ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 46InBlock.gif/// This logon type is intended for high performance servers to authenticate clear text passwords. 
 47InBlock.gif/// The LogonUser function does not cache credentials for this logon type. 
 48ExpandedSubBlockEnd.gif/// </summary> 

 49InBlock.gifLOGON32_LOGON_NETWORK = 3
 50InBlock.gif
 51ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 52InBlock.gif/// This logon type is intended for batch servers, where processes may be executing on behalf of a user 
 53InBlock.gif/// without their direct intervention; or for higher performance servers that process many clear-text 
 54InBlock.gif/// authentication attempts at a time, such as mail or web servers. The LogonUser function does not cache 
 55InBlock.gif/// credentials for this logon type. 
 56ExpandedSubBlockEnd.gif/// </summary> 

 57InBlock.gifLOGON32_LOGON_BATCH = 4
 58InBlock.gif
 59ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 60InBlock.gif/// Indicates a service-type logon. The account provided must have the service privilege enabled. 
 61ExpandedSubBlockEnd.gif/// </summary> 

 62InBlock.gifLOGON32_LOGON_SERVICE = 5
 63InBlock.gif
 64ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 65InBlock.gif/// This logon type is intended for GINA DLLs logging on users who will be interactively using the computer. 
 66InBlock.gif/// This logon type allows a unique audit record to be generated that shows when the workstation was unlocked. 
 67ExpandedSubBlockEnd.gif/// </summary> 

 68InBlock.gifLOGON32_LOGON_UNLOCK = 7
 69InBlock.gif
 70ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 71InBlock.gif/// Windows XP/2000: This logon type preserves the name and password in the authentication packages, 
 72InBlock.gif/// allowing the server to make connections to other network servers while impersonating the client. 
 73InBlock.gif/// This allows a server to accept clear text credentials from a client, call LogonUser, verify that 
 74InBlock.gif/// the user can access the system across the network, and still communicate with other servers. 
 75ExpandedSubBlockEnd.gif/// </summary> 

 76InBlock.gifLOGON32_LOGON_NETWORK_CLEARTEXT = 8
 77InBlock.gif
 78ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 79InBlock.gif/// Windows XP/2000: This logon type allows the caller to clone its current token and specify new credentials 
 80InBlock.gif/// for outbound connections. The new logon session has the same local identity, but uses different credentials 
 81InBlock.gif/// for other network connections. 
 82InBlock.gif/// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider. 
 83ExpandedSubBlockEnd.gif/// </summary> 

 84InBlock.gifLOGON32_LOGON_NEW_CREDENTIALS = 9 
 85ExpandedSubBlockEnd.gif}

 86InBlock.gif
 87InBlock.gifpublic enum LogonProvider : int 
 88ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
 89ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 90InBlock.gif/// Use the standard logon provider for the system. The default security provider is NTLM. 
 91InBlock.gif/// Windows XP: The default provider is negotiate, unless you pass NULL for the domain name and 
 92InBlock.gif/// the user name is not in UPN format. In this case the default provider is NTLM. 
 93ExpandedSubBlockEnd.gif/// </summary> 

 94InBlock.gifLOGON32_PROVIDER_DEFAULT = 0
 95InBlock.gif
 96ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
 97InBlock.gif/// Use the Windows NT 3.5 logon provider. 
 98ExpandedSubBlockEnd.gif/// </summary> 

 99InBlock.gifLOGON32_PROVIDER_WINNT35 = 1
100InBlock.gif
101ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
102InBlock.gif/// Use the NTLM logon provider. 
103ExpandedSubBlockEnd.gif/// </summary> 

104InBlock.gifLOGON32_PROVIDER_WINNT40 = 2
105InBlock.gif
106ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
107InBlock.gif/// Windows XP/2000: Use the negotiate logon provider. 
108ExpandedSubBlockEnd.gif/// </summary> 

109InBlock.gifLOGON32_PROVIDER_WINNT50 = 3 
110ExpandedSubBlockEnd.gif}

111InBlock.gif
112InBlock.gifclass SecuUtil32 
113ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
114InBlock.gif[DllImport("advapi32.dll", SetLastError=true)] 
115InBlock.gifpublic static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, 
116InBlock.gifint dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle); 
117InBlock.gif
118InBlock.gif[DllImport("kernel32.dll", CharSet=CharSet.Auto)] 
119InBlock.gifpublic extern static bool CloseHandle(IntPtr handle); 
120InBlock.gif
121InBlock.gif[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] 
122InBlock.gifpublic extern static bool DuplicateToken(IntPtr ExistingTokenHandle, 
123InBlock.gifint SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); 
124ExpandedSubBlockEnd.gif}
 
125InBlock.gif
126InBlock.gifpublic class NetworkSecurity 
127ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
128InBlock.gifpublic NetworkSecurity() 
129ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
130InBlock.gif// 
131InBlock.gif// TODO: Add constructor logic here 
132InBlock.gif// 
133ExpandedSubBlockEnd.gif}
 
134InBlock.gif
135ExpandedSubBlockStart.gifContractedSubBlock.gif/**//// <summary> 
136InBlock.gif/// The ImpersonateUser function attempts to log a user on to the local computer. 
137InBlock.gif/// The local computer is the computer from which ImpersonateUser was called. 
138InBlock.gif/// You cannot use ImpersonateUser to log on to a remote computer. 
139InBlock.gif/// You specify the user with a user name and domain, and authenticate the user with a clear-text password. 
140InBlock.gif/// If the function succeeds, you receive a handle to a token that represents the logged-on user. 
141InBlock.gif/// You can then use this token handle to impersonate the specified user, or in most cases, 
142InBlock.gif/// to create a process running in the context of the specified user. 
143InBlock.gif/// </summary> 
144InBlock.gif/// <param name="strDomain"> 
145InBlock.gif/// specifies the name of the domain or server whose account database contains the strLogin account. 
146InBlock.gif/// </param> 
147InBlock.gif/// <param name="strLogin">specifies the name of the user.</param> 
148InBlock.gif/// <param name="strPwd">specifies the clear-text password for the user account specified by strLogin.</param> 
149InBlock.gif/// <param name="logonType">Specifies the type of logon operation to perform.</param> 
150InBlock.gif/// <param name="logonProvider">Specifies the logon provider.</param> 
151InBlock.gif/// <example> 
152InBlock.gif/// //Add System.Security.dll 
153InBlock.gif/// //using System.Security.Principal; 
154InBlock.gif/// 
155InBlock.gif/// string strDomain=ConfigurationSettings.AppSettings["mSALoginDomainName"]; 
156InBlock.gif/// string strUser=ConfigurationSettings.AppSettings["mSALoginDomainUser"]; 
157InBlock.gif/// string strPassword=ConfigurationSettings.AppSettings["mSALoginDomainPassword"]; 
158InBlock.gif/// 
159InBlock.gif/// WindowsImpersonationContext impContext = null; 
160InBlock.gif/// try 
161InBlock.gif/// { 
162InBlock.gif/// impContext = NetworkSecurity.ImpersonateUser(strDomain,strUser,strPassword, 
163InBlock.gif/// LogonType.LOGON32_LOGON_SERVICE, 
164InBlock.gif/// LogonProvider.LOGON32_PROVIDER_DEFAULT); 
165InBlock.gif/// } 
166InBlock.gif/// catch 
167InBlock.gif/// { 
168InBlock.gif/// 
169InBlock.gif/// } 
170InBlock.gif/// 
171InBlock.gif/// //work under this logined user 
172InBlock.gif/// 
173InBlock.gif/// impContext.Undo(); 
174InBlock.gif/// </example> 
175InBlock.gif/// <returns> 
176ExpandedSubBlockEnd.gif/// </returns> 

177InBlock.gifpublic static WindowsImpersonationContext ImpersonateUser(string strDomain, 
178InBlock.gifstring strLogin, 
179InBlock.gifstring strPwd, 
180InBlock.gifLogonType logonType, 
181InBlock.gifLogonProvider logonProvider) 
182ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
183InBlock.gif// Initialize tokens 
184InBlock.gifIntPtr tokenHandle = new IntPtr(0); 
185InBlock.gifIntPtr dupeTokenHandle = new IntPtr(0); 
186InBlock.giftokenHandle = IntPtr.Zero; 
187InBlock.gifdupeTokenHandle = IntPtr.Zero; 
188InBlock.gif
189InBlock.gif// If domain name was blank, assume local machine 
190InBlock.gifif (strDomain == ""
191InBlock.gifstrDomain = System.Environment.MachineName; 
192InBlock.gif
193InBlock.giftry 
194ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
195InBlock.gifconst int SecurityImpersonation = 2
196InBlock.gif
197InBlock.gif// Call LogonUser to obtain a handle to an access token. 
198InBlock.gifbool returnValue = SecuUtil32.LogonUser( 
199InBlock.gifstrLogin, 
200InBlock.gifstrDomain, 
201InBlock.gifstrPwd, 
202InBlock.gif(int)logonType, 
203InBlock.gif(int)logonProvider, 
204InBlock.gifref tokenHandle); 
205InBlock.gif
206InBlock.gif// Did impersonation fail? 
207InBlock.gifif (false == returnValue) 
208ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
209InBlock.gifint ret = Marshal.GetLastWin32Error(); 
210InBlock.gif// Throw the exception show the reason why LogonUser failed 
211InBlock.gifstring strErr = String.Format("LogonUser failed with error code : {0}", ret); 
212InBlock.gifthrow new ApplicationException(strErr, null); 
213ExpandedSubBlockEnd.gif}
 
214InBlock.gif
215InBlock.gif// Get identity before impersonation 
216InBlock.gifbool retVal = SecuUtil32.DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle); 
217InBlock.gif
218InBlock.gif// Did DuplicateToken fail? 
219InBlock.gifif (false == retVal) 
220ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
221InBlock.gif// Close existing handle 
222InBlock.gifSecuUtil32.CloseHandle(tokenHandle); 
223InBlock.gif// Throw the exception show the reason why DuplicateToken failed 
224InBlock.gifthrow new ApplicationException("Failed to duplicate token"null); 
225ExpandedSubBlockEnd.gif}
 
226InBlock.gif
227InBlock.gif// Create new identity using new primary token 
228InBlock.gif// The token that is passed to the following constructor must 
229InBlock.gif// be a primary token in order to use it for impersonation. 
230InBlock.gifWindowsIdentity newId = new WindowsIdentity(dupeTokenHandle); 
231InBlock.gifWindowsImpersonationContext impersonatedUser = newId.Impersonate(); 
232InBlock.gif
233InBlock.gifreturn impersonatedUser; 
234ExpandedSubBlockEnd.gif}
 
235InBlock.gifcatch (Exception ex) 
236ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
237InBlock.gifthrow new ApplicationException(ex.Message, ex); 
238ExpandedSubBlockEnd.gif}
 
239InBlock.giffinally 
240ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif
241InBlock.gif// Close handle 
242InBlock.gifif (tokenHandle != IntPtr.Zero) 
243InBlock.gifSecuUtil32.CloseHandle(tokenHandle); 
244InBlock.gifif (dupeTokenHandle != IntPtr.Zero) 
245InBlock.gifSecuUtil32.CloseHandle(dupeTokenHandle); 
246ExpandedSubBlockEnd.gif}
 
247ExpandedSubBlockEnd.gif}
 
248ExpandedSubBlockEnd.gif}
 
249ExpandedBlockEnd.gif}
 
250 None.gif 
251 None.gif 
252 None.gif

None.gif <% @ Page Language = " C# " %>
None.gif
<% @ Import Namespace  =   " System.Web "   %>
None.gif
<% @ Import Namespace  =   " System.Web.Security "   %>
None.gif
<% @ Import Namespace  =   " System.Security.Principal "   %>
None.gif
<% @ Import Namespace  =   " System.Runtime.InteropServices "   %>
None.gif
None.gif
< script runat = server >
None.gif
public   const   int  LOGON32_LOGON_INTERACTIVE  =   2 ;
None.gif
public   const   int  LOGON32_PROVIDER_DEFAULT  =   0 ;
None.gif
None.gifWindowsImpersonationContext impersonationContext;
None.gif
None.gif[DllImport(
" advapi32.dll " )]
None.gif
public   static   extern   int  LogonUserA(String lpszUserName,
None.gif    String lpszDomain,
None.gif    String lpszPassword,
None.gif    
int  dwLogonType,
None.gif    
int  dwLogonProvider,
None.gif    
ref  IntPtr phToken);
None.gif[DllImport(
" advapi32.dll " , CharSet = CharSet.Auto, SetLastError = true )]
None.gif
public   static   extern   int  DuplicateToken(IntPtr hToken,
None.gif    
int  impersonationLevel,
None.gif    
ref  IntPtr hNewToken);
None.gif
None.gif[DllImport(
" advapi32.dll " , CharSet = CharSet.Auto, SetLastError = true )]
None.gif
public   static   extern   bool  RevertToSelf();
None.gif
None.gif[DllImport(
" kernel32.dll " , CharSet = CharSet.Auto)]
None.gif
public   static   extern    bool  CloseHandle(IntPtr handle);
None.gif
None.gif
public   void  Page_Load(Object s, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
if(impersonateValidUser("username""domain""password"))
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
//Insert your code that runs under the security context of a specific user here.
InBlock.gif
        undoImpersonation();
ExpandedSubBlockEnd.gif    }

InBlock.gif    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
//Your impersonation failed. Therefore, include a fail-safe mechanism here.
ExpandedSubBlockEnd.gif
    }

ExpandedBlockEnd.gif}

None.gif
None.gif
private   bool  impersonateValidUser(String userName, String domain, String password)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    WindowsIdentity tempWindowsIdentity;
InBlock.gif    IntPtr token 
= IntPtr.Zero;
InBlock.gif    IntPtr tokenDuplicate 
= IntPtr.Zero;
InBlock.gif
InBlock.gif    
if(RevertToSelf())
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
InBlock.gif            LOGON32_PROVIDER_DEFAULT, 
ref token) != 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if(DuplicateToken(token, 2ref tokenDuplicate) != 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                tempWindowsIdentity 
= new WindowsIdentity(tokenDuplicate);
InBlock.gif                impersonationContext 
= tempWindowsIdentity.Impersonate();
InBlock.gif                
if (impersonationContext != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    CloseHandle(token);
InBlock.gif                    CloseHandle(tokenDuplicate);
InBlock.gif                    
return true;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif    
if(token!= IntPtr.Zero)
InBlock.gif        CloseHandle(token);
InBlock.gif    
if(tokenDuplicate!=IntPtr.Zero)
InBlock.gif        CloseHandle(tokenDuplicate);
InBlock.gif    
return false;
ExpandedBlockEnd.gif}

None.gif
None.gif
private   void  undoImpersonation()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    impersonationContext.Undo();
ExpandedBlockEnd.gif}

None.gif
</ script >
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值