首页 > 解决方案 > 在 .Net Core 中模拟用户

问题描述

我正在尝试模拟 .NET 核心中的用户将文件直接复制到共享驱动器。我已经在网上查找并复制和更改了代码,但我的登录功能不起作用。

这是代码

 #region Impersionation global variables
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);
        #endregion

模拟功能

 private bool ImpersonateUser(string domain, string userName, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;


            if (RevertToSelf())
            {
//This logonUserA does not run correctly
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);

                        WindowsIdentity.RunImpersonated(tempWindowsIdentity.AccessToken,() =>
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                        });

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

LogonUserA 函数未正确登录。我正确地传递了域名、用户名和密码,但它仍然不起作用。

任何想法将不胜感激

标签: c#asp.netasp.net-coreasp.net-identityimpersonation

解决方案


推荐阅读