前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >windows logon API

windows logon API

作者头像
阿新
发布2018-04-12 17:57:47
9180
发布2018-04-12 17:57:47
举报
文章被收录于专栏:c#开发者c#开发者

using System; using System.Collections.Generic; using System.Text; using System.ComponentModel;

using System.Security; using System.Security.Principal; using System.Runtime; using System.Runtime.InteropServices;

using System.Web; using System.Web.Security;

namespace Impersonate {     [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)] struct _USE_INFO_2 {   internal string ui2_local;   internal string ui2_remote;   internal IntPtr ui2_password; // don't pass a string or StringBuilder here!!   internal uint ui2_status;   internal uint ui2_asg_type;   internal uint ui2_refcount;   internal uint ui2_usecount;   internal string ui2_username;   internal string ui2_domainname; } class WinNet {   [DllImport("netapi32", CharSet=CharSet.Auto, SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]   static extern int NetUseAdd(    string UncServerName, // not used    int Level,  // use info struct level 1 or 2    IntPtr Buf,  // Buffer    ref int ParmError   );   const uint USE_WILDCARD = 0xFFFFFFFF;

  // Establish a use record   public static void UseRecord(string resource, string user, string password, string domain)   {    int ret = 0;    int paramError = 0;    _USE_INFO_2 use2 = new _USE_INFO_2();    IntPtr pBuf = IntPtr.Zero;    use2.ui2_password = IntPtr.Zero;    try    {     pBuf = Marshal.AllocHGlobal(Marshal.SizeOf(use2));     use2.ui2_local = null;     use2.ui2_asg_type = USE_WILDCARD;     use2.ui2_remote = resource;     use2.ui2_password = Marshal.StringToHGlobalAuto(password);     use2.ui2_username = user;     use2.ui2_domainname = domain;     Marshal.StructureToPtr(use2, pBuf, true);     ret = NetUseAdd(null, 2, pBuf, ref paramError);     if(ret != 0)     {          throw new Exception(new Win32Exception(Marshal.GetLastWin32Error()).Message);     }    }    finally    {     Marshal.FreeHGlobal(use2.ui2_password);     Marshal.FreeHGlobal(pBuf);    }   } }

    class Program     {         [System.Runtime.InteropServices.DllImport("advapi32.dll")]         public static extern int LogonUser(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);

        const int LOGON32_PROVIDER_DEFAULT = 0;         const int LOGON32_LOGON_INTERACTIVE = 2;

        static public WindowsImpersonationContext wic;

        //static void Main(string[] args)         //{         //    IntPtr lnToken;

        //    if (ImpersonateValidUser("michaell", "cmp-0641", "wilma"))         //    {         //        using (wic)         //        {

        //            string dir = @"\\cmp-0641\C$\" + "Test";         //            System.IO.Directory.CreateDirectory(dir);         //        }

        //        StringBuilder sb = new StringBuilder(80, 80);         //        RevertToSelf();         //        //CloseHandle( lnToken );         //    }         //    else         //    {

        //    }         //    return;         //}

        static public bool ImpersonateValidUser(String userName, String domain, String password)         {             WindowsIdentity wi;             IntPtr token = IntPtr.Zero;             IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())             {                 if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,                     LOGON32_PROVIDER_DEFAULT, ref token) != 0)                 {                     if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)                     {                         wi = new WindowsIdentity(tokenDuplicate);                         wic = wi.Impersonate();                         if (wic != null)                         {                             CloseHandle(token);                             CloseHandle(tokenDuplicate);                             return true;                         }                     }                 }             }             if (token != IntPtr.Zero)                 CloseHandle(token);             if (tokenDuplicate != IntPtr.Zero)                 CloseHandle(tokenDuplicate);             return false;         }

    }

    public class LogOnUser     {         //LogonUser parameters         [DllImport("advapi32.dll")]         private static extern bool LogonUser(String lpszUsername,                                                 String lpszDomain,                                                 String lpszPassword,                                                 int dwLogonType,                                                 int dwLogonProvider,                                                 ref IntPtr phToken);

        //CloseHandle parameters. When you are finished,         //free the memory allocated for the handle.         [DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]         private static extern bool CloseHandle(IntPtr handle);

        public static WindowsIdentity GetWindowsIdentity(string pUserName, string pDomain)         {             return null;         }

        public static WindowsIdentity GetWindowsIdentity(string pUserName, string pDomain, string pPassword)         {             IntPtr tokenHandle = IntPtr.Zero;

            try             {                 const int LOGON32_PROVIDER_DEFAULT = 0;                 const int LOGON32_LOGON_NETWORK = 5;

                //Call LogonUser to obtain a                 //handle to an access token                 bool returnValue = LogonUser(pUserName, pDomain,                              pPassword,                             LOGON32_LOGON_NETWORK,                            LOGON32_PROVIDER_DEFAULT,                             ref tokenHandle);

                if (false == returnValue)                 {                     return null;                 }

                ////Check the identity                 //Console.WriteLine("Before impersonation: " +                 //         WindowsIdentity.GetCurrent().Name);

                //Create a WindowsIdentity from the impersonation                 //token, then impersonate the user.                 WindowsIdentity newId;                 newId = new WindowsIdentity(tokenHandle);                 return newId;             }

            catch (Exception ex)             {                 // TODO log the Exception Message.                 return null;             }         }

    }

}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2008-05-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档