如何冒充其他用户?

时间:2010-02-17 17:36:49

标签: c# asp.net impersonation windows-identity advapi32

我正在开发一个ASP.net应用程序,我正在尝试冒充用户

我正在使用令牌

创建一个windowsIdentity
WindowsIdentity winId = new WindowsIdenty( token );

这个令牌是通过调用un托管代码获得的

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

有没有其他方法可以在不使用此advapi32.dll非托管代码的情况下获取令牌?

TKS

2 个答案:

答案 0 :(得分:3)

就个人而言,我更喜欢使用wrapper class来处理此假冒行为。

因此,您将使用非托管代码,但AFAIK无法直接使用托管代码执行此操作。

答案 1 :(得分: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();