• 用户身份模拟


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Security.Principal;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var impersonation = new ImpersonatedUser("lenovo", "", "123456", ImpersonatedUser.LogonType.Interactive))
                {
                    //code here
                }
            }
        }
    
        public class ImpersonatedUser : IDisposable
        {
            IntPtr userHandle;
            WindowsImpersonationContext impersonationContext;
    
            public ImpersonatedUser(string user, string domain, string password, LogonType logonType = LogonType.Interactive)
            {
                userHandle = IntPtr.Zero;
                bool loggedOn = LogonUser(
                    user,
                    domain,
                    password,
                    LogonType.Interactive,
                    LogonProvider.Default,
                    out userHandle);
    
                if (!loggedOn)
                    throw new Win32Exception(Marshal.GetLastWin32Error());
    
                // Begin impersonating the user
                impersonationContext = WindowsIdentity.Impersonate(userHandle);
            }
    
            public void Dispose()
            {
                if (userHandle != IntPtr.Zero)
                {
                    CloseHandle(userHandle);
                    userHandle = IntPtr.Zero;
                    impersonationContext.Undo();
                }
            }
    
            [DllImport("advapi32.dll", SetLastError = true)]
            static extern bool LogonUser(
                string lpszUsername,
                string lpszDomain,
                string lpszPassword,
                LogonType dwLogonType,
                LogonProvider dwLogonProvider,
                out IntPtr phToken
                );
    
            [DllImport("kernel32.dll", SetLastError = true)]
            static extern bool CloseHandle(IntPtr hHandle);
    
            public enum LogonType : int
            {
                Interactive = 2,
                Network = 3,
                Batch = 4,
                Service = 5,
                NetworkCleartext = 8,
                NewCredentials = 9,
            }
    
            enum LogonProvider : int
            {
                Default = 0,
            }
        }
    
    }
  • 相关阅读:
    自动跳转至首页(Java Script)
    简单的轮播图(Java Script)
    蓝桥杯 2016年 第七届 四平方和(JAVA)
    蓝桥杯 2016年 第七届 剪邮票(JAVA)
    蓝桥杯 2015年 第六届 生命之树(JAVA)
    蓝桥杯 2015年 第六届 垒骰子(JAVA)
    numpy笔记
    opencv安装和运行
    vs code环境配置注意点
    numpy中matrix使用方法
  • 原文地址:https://www.cnblogs.com/nanfei/p/5105350.html
Copyright © 2020-2023  润新知