2010-02-17 45 views
5

我工作的一個ASP.net應用程序,我試圖模擬用戶如何模仿其他用戶?

我創建的WindowsIdentity使用令牌

WindowsIdentity winId = new WindowsIdenty(token); 

此令牌是由呼叫管理未拿到代碼

[DllImport("advapi32.dll")] 
public static extern int LogonUserA(String lpszUserName, 
    String lpszDomain, 
    String lpszPassword, 
    int dwLogonType, 
    int dwLogonProvider, 
    ref IntPtr phToken); 

是否有任何其他方式獲得令牌,而不使用此advapi32.dll非託管代碼?

TKS

+0

有更多的Win32 API的方式。 – 2010-02-17 17:38:49

回答

3

就個人而言,我更喜歡wrapper class來處理這個模擬。

因此,您將使用非託管代碼,但AFAIK無法直接使用託管代碼執行此操作。

+0

你的包裝類代碼工作得很好。簡單的剪切和粘貼。謝謝! – 2014-08-05 15:56:03

2

內置一顆類:Impersonate.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Security; 
using System.Security.Principal; 
using System.Runtime.InteropServices; 
using System.IO; 
using System.Text; 

using System.Web; 

// you must change the YourProgramName 

namespace [YourProgramName] 
{ 
    public class Impersonate 
    { 

     [DllImport("advapi32.dll", SetLastError = true)] 
     private static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, 
              int dwLogonType, int dwLogonProvider, out int phToken); 

     [DllImport("kernel32.dll")] 
     private static extern int FormatMessage(int dwFlags, string lpSource, int dwMessageId, int dwLanguageId, 
               StringBuilder lpBuffer, int nSize, string[] Arguments); 


     private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8; 
     private const int LOGON32_PROVIDER_DEFAULT = 0; 
     private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000; 

     private static WindowsImpersonationContext winImpersonationContext = null; 

     public static void ImpersonateUser(string domain, string userName, string password) 
     { 

      //Benutzer einloggen 
      int userToken = 0; 

      bool loggedOn = (LogonUser(userName, domain, password, LOGON32_LOGON_NETWORK_CLEARTEXT, 
             LOGON32_PROVIDER_DEFAULT, out userToken) != 0); 

      if (loggedOn == false) 
      { 
       int apiError = Marshal.GetLastWin32Error(); 
       StringBuilder errorMessage = new StringBuilder(1024); 
       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, null, apiError, 0, errorMessage, 1024, null); 
       throw new Exception(errorMessage.ToString()); 
      } 

      WindowsIdentity identity = new WindowsIdentity((IntPtr)userToken); 
      winImpersonationContext = identity.Impersonate(); 

     } 

     public static void UndoImpersonation() 
     { 
      if (winImpersonationContext != null) 
      { 
       winImpersonationContext.Undo(); 
      } 
     } 

    } 
} 

在程序中使用:

Impersonate.ImpersonateUser("Domain", "Username", "UserPassword"); 

        //Your Code as the new User 

       Impersonate.UndoImpersonation();