示例#1
0
        //TODO: Should be internal.  Need to figure out how to get to the companies list before they are fully auth'd.
        //        public ImpersonationData ImpersonateMasterUser()
        //        {
        //            ImpersonationData impData = DoImpersonation(Registry.GetInitialCredentials());
        //            impData.Identity.Impersonate();
        //            return impData;
        //        }
        ImpersonationData DoImpersonation(NTCredential credential)
        {
            IntPtr tokenHandle = new IntPtr(0);
            IntPtr dupeTokenHandle = new IntPtr(0);
            WindowsImpersonationContext impersonatedUser = null;
            // Get the user token for the specified user, machine, and password using the
            // unmanaged LogonUser method.
            const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
            const int LOGON32_LOGON_INTERACTIVE = 2;
            //const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
            //const int LOGON32_PROVIDER_WINNT50 = 3;
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            //const int LOGON32_LOGON_NETWORK = 3;
            const int SecurityImpersonation = 2;
            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(credential.UserName, credential.DomainName, credential.Password,
                LOGON32_LOGON_INTERACTIVE , LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new Exception(String.Format("LogonUser failed with error code : {0}, message: {1}", ret, GetErrorMessage(ret)));
            }

            bool retVal = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
            if (false == retVal)
            {
                CloseHandle(tokenHandle);
            }

            // The token that is passed to the following constructor must
            // be a primary token in order to use it for impersonation.
            WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
            impersonatedUser = newId.Impersonate();
            return new ImpersonationData(tokenHandle,dupeTokenHandle,newId,impersonatedUser);
        }
示例#2
0
 public ImpersonationData Impersonate(NTCredential credential)
 {
     return DoImpersonation(credential);
 }