windows logon API

來源:互聯網
上載者:User

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;
            }
        }

    }

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.