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

4

2 回答 2

3

建了一个类: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();
于 2012-07-24T07:51:53.433 回答
3

就个人而言,我更喜欢包装类来处理这种模拟。

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

于 2010-02-17T17:42:05.240 回答