首页 >> C#.NET >> 正文
如何扮演另一个帐号(C#实现)
来源:Dotnet频道 作者:采集 时间:2008-3-31

如何扮演另一个帐号(C#实现)
 

using directives#region Using directives

using System;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
#endregion

namespace Impersonal
{
    class Program
    {
        测试代码#region 测试代码
        public static void Main(string[] args)
        {
            Console.WriteLine("当前用户是: "
    + WindowsIdentity.GetCurrent().Name);
            ImpersonatedWork testDel = new ImpersonatedWork(Test);
            ImpersonateAndDo("epro\\liping", "88888888", testDel);
            Console.WriteLine("当前用户是: "
    + WindowsIdentity.GetCurrent().Name);
        }
        static void Test()
        {
            Console.WriteLine("当前用户是: "
                + WindowsIdentity.GetCurrent().Name);
        }
        #endregion

        [DllImport("advapi32.dll", SetLastError = true)]
        public extern static bool LogonUser(String lpszUsername, String lpszDomain,
            String lpszPassword, int dwLogonType,
            int dwLogonProvider, ref IntPtr phToken);

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

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
            int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

        public delegate void ImpersonatedWork();
        /**//// <summary>
        /// 以指定用户的身份去做一件事情
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="PWD"></param>
        /// <param name="WhatToDo"></param>
        public static void ImpersonateAndDo(string UserName, string PWD, ImpersonatedWork WhatToDo)
        {
            扮演用户#region 扮演用户
            string domainName = string.Empty;
            string userName = string.Empty;
            IntPtr tokenHandle = new IntPtr(0);
            IntPtr dupeTokenHandle = new IntPtr(0);
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_INTERACTIVE = 2;
            const int SecurityImpersonation = 2;
            if (! Regex.IsMatch(UserName, @"^\w+[\\]?\w+$"))
            {
                throw new ApplicationException("非法的用户名");
            }
            string[] tmp = UserName.Split(new char[] { '\\' });
            if (tmp.Length > 1)
            {
                domainName = tmp[0];
                userName = tmp[1];
            }
            else
            {
                userName = tmp[0];
            }
            tokenHandle = IntPtr.Zero;
            dupeTokenHandle = IntPtr.Zero;
            bool returnValue = LogonUser(userName,domainName,  PWD,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);
            if (!returnValue)
            {
                throw new ApplicationException("取Handle出错了!");
            }

            //Console.WriteLine("当前用户是: "
            //    + WindowsIdentity.GetCurrent().Name);

            bool retVal = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
            if (!retVal)
            {
                CloseHandle(tokenHandle);
                throw new ApplicationException("复制Handle出错了!");
            }
            WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
            WindowsImpersonationContext impersonatedUser = newId.Impersonate();
            #endregion
            以新用户身份调用#region 以新用户身份调用
            WhatToDo();
            #endregion
            取消扮演#region 取消扮演
            impersonatedUser.Undo();
            if (tokenHandle != IntPtr.Zero)
                CloseHandle(tokenHandle);
            if (dupeTokenHandle != IntPtr.Zero)
                CloseHandle(dupeTokenHandle);
            #endregion
        }
    }
}

相关新闻
相关评论
 
评论表单加载中...
 
C#.NET文章

 在Visual C++应

 编辑:admin

 时间:2008-3-10


   .NET Framework 中多语言支持的实现-.NET Framework
   将Eiffel系统集成到.NET Framework中-.NET Framework
   04年五种常用RAD的测验比较(1)-.NET Framework
   04年五种常用RAD的测验比较(2)-.NET Framework
   04年五种常用RAD的测验比较(3)-.NET Framework
最新文章
   .NET Framework 中多语言支持的实现-.NET Framework
   将Eiffel系统集成到.NET Framework中-.NET Framework
   04年五种常用RAD的测验比较(1)-.NET Framework
   04年五种常用RAD的测验比较(2)-.NET Framework
   04年五种常用RAD的测验比较(3)-.NET Framework
总站搜索
搜索
 
热门文章
   oracle数据库文件中的导入\导出
   用Oracle10g列值掩码技术隐藏敏感数据
   VB程序中用ADO对象动态创建数据库和表-VB.NET
   用VB6写简单程序 让电骡自动关机-VB.NET
   使用.NET2.0编写COM组件供VB调用-VB.NET
   VB.NET:键盘控制焦点移动-VB.NET
   用VB.NET绘制GDI图形-VB.NET
   vb.net中应用 ArrayList 实例-VB.NET
 
推荐文章
ASP.NET中的状态管理-ASP.NET
VC、IE、ASP环境下打印、预备的完美解决方案
oracle数据库文件中的导入\导出
VB.NET中快速访问注册表技巧-VB.NET
在vb中实现超连接的方法!和直接发邮件-VB.NET
用VB做realplayer播放列表-VB.NET
在VB.NET中如何实现和利用SortedLists-VB.NET
利用VB.NET Stopwatch对象记录时间-VB.NET
成都古羌科技有限公司版权所有: Copyright@2007-2010 ,ALL Rights Reserved 蜀ICP备07017240号