当前位置: 首页>>代码示例>>C#>>正文


C# WindowsIdentity.Impersonate方法代码示例

本文整理汇总了C#中System.Security.Principal.WindowsIdentity.Impersonate方法的典型用法代码示例。如果您正苦于以下问题:C# WindowsIdentity.Impersonate方法的具体用法?C# WindowsIdentity.Impersonate怎么用?C# WindowsIdentity.Impersonate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Principal.WindowsIdentity的用法示例。


在下文中一共展示了WindowsIdentity.Impersonate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Enter

 public void Enter()
 {
     if (this.IsInContext) return;
     m_Token = new IntPtr(0);
     try
     {
         m_Token = IntPtr.Zero;
         bool logonSuccessfull = LogonUser(
            m_Username,
            m_Domain,
            m_Password,
            LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT,
            ref m_Token);
         if (logonSuccessfull == false)
         {
             int error = Marshal.GetLastWin32Error();
             throw new Win32Exception(error);
         }
         WindowsIdentity identity = new WindowsIdentity(m_Token);
         m_Context = identity.Impersonate();
     }
     catch (Exception exception)
     {
         // Catch exceptions here
     }
 }
开发者ID:nathantownsend,项目名称:myCoal,代码行数:27,代码来源:WrapperImpersonationContext.cs

示例2: WindowsImpersonatedIdentity

 /// <summary>
 ///   Constructor. Starts the impersonation with the given credentials. Please note that the account that instantiates the Impersonator class needs to have the 'Act as part of operating system' privilege set.
 /// </summary>
 /// <param name="userName"> The name of the user to act as. </param>
 /// <param name="domainName"> The domain name of the user to act as. </param>
 /// <param name="password"> The password of the user to act as. </param>
 public WindowsImpersonatedIdentity(string userName, string domainName, string password)
 {
     var token = IntPtr.Zero;
     var tokenDuplicate = IntPtr.Zero;
     try {
         if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(domainName) && string.IsNullOrEmpty(password)) {
             identity = WindowsIdentity.GetCurrent();
         } else {
             if (LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) {
                 if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) {
                     identity = new WindowsIdentity(tokenDuplicate);
                     impersonationContext = identity.Impersonate();
                 } else {
                     throw new Win32Exception(Marshal.GetLastWin32Error());
                 }
             } else {
                 throw new Win32Exception(Marshal.GetLastWin32Error());
             }
         }
     } finally {
         if (token != IntPtr.Zero) {
             CloseHandle(token);
         }
         if (tokenDuplicate != IntPtr.Zero) {
             CloseHandle(tokenDuplicate);
         }
     }
 }
开发者ID:virmitio,项目名称:coapp,代码行数:34,代码来源:Impersonation.cs

示例3: Impersonate

 public void Impersonate(string domainName, string userName, string password){
     //try
     {
         // Use the unmanaged LogonUser function to get the user token for
         // the specified user, domain, and password.
         const int LOGON32_PROVIDER_DEFAULT = 0;
         // Passing this parameter causes LogonUser to create a primary token.
         const int LOGON32_LOGON_INTERACTIVE = 2;
         tokenHandle = IntPtr.Zero;
         // ---- Step - 1
         // Call LogonUser to obtain a handle to an access token.
         bool returnValue = LogonUser(
                                 userName,
                                 domainName,
                                 password,
                                 LOGON32_LOGON_INTERACTIVE,
                                 LOGON32_PROVIDER_DEFAULT,
                                 ref tokenHandle); // tokenHandle - new security token
         if (false == returnValue){
             int ret = Marshal.GetLastWin32Error();
             throw new System.ComponentModel.Win32Exception(ret);
         }
         // ---- Step - 2
         WindowsIdentity newId = new WindowsIdentity(tokenHandle);
         // ---- Step - 3
         {
             impersonatedUser = newId.Impersonate();
         }
     }
 }
开发者ID:MichelKansou,项目名称:RedXProject,代码行数:30,代码来源:Impersonate.cs

示例4: Impersonate

        /// <summary>
        /// 사용자를 가장합니다.
        /// </summary>
        /// <param name="userName">사용자 이름 입니다.</param>
        /// <param name="domain">도메인 이름 입니다.</param>
        /// <param name="password">암호 입니다.</param>
        /// /// <exception cref="SecurityException">가장이 실패할 경우 <c>SecurityException</c>를 던집니다.</exception>
        public void Impersonate(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return;
                        }
                    }
                }
            }

            if (token != IntPtr.Zero) CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);

            throw new SecurityException("사용자를 가장하는데 실패했습니다.");
        }
开发者ID:tomochandv,项目名称:Test,代码行数:37,代码来源:Identity.cs

示例5: Impersonate

        public bool Impersonate(string userName, string domain, string password)
        {
            var token = IntPtr.Zero;
            var tokenDuplicate = IntPtr.Zero;

            if(RevertToSelf())
            {
                if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out token))
                {
                    if(DuplicateToken(token, 2, out tokenDuplicate) != 0)
                    {
                        var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        _impersonationContext = tempWindowsIdentity.Impersonate();
                        if(_impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if(token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            if(tokenDuplicate != IntPtr.Zero)
            {
                CloseHandle(tokenDuplicate);
            }
            return false;
        }
开发者ID:Robin--,项目名称:Warewolf,代码行数:32,代码来源:Impersonator.cs

示例6: PerformImpersonatedTask

 //Public Sub PerformImpersonatedTask(ByVal username As String, ByVal domain As String, ByVal password As String, ByVal logonType As Integer, ByVal logonProvider As Integer, ByVal methodToPerform As Action)
 public void PerformImpersonatedTask(string username, string domain, string password, int logonType, int logonProvider, Action methodToPerform)
 {
     IntPtr token = IntPtr.Zero;
     if (RevertToSelf())
     {
         if (LogonUser(username, domain, password, logonType, logonProvider, ref token) != 0)
         {
             dynamic identity = new WindowsIdentity(token);
             dynamic impersonationContext = identity.Impersonate();
             if (impersonationContext != null)
             {
                 methodToPerform.Invoke();
                 impersonationContext.Undo();
             }
             // do logging
         }
         else
         {
         }
     }
     if (token != IntPtr.Zero)
     {
         CloseHandle(token);
     }
 }
开发者ID:robinsone,项目名称:WesternEngineering,代码行数:26,代码来源:impersonator.cs

示例7: Impersonate

 public void Impersonate()
 {
     //create identity
     WindowsIdentity newId = new WindowsIdentity(this.tokenHandle);
     //start impersonating
     this.impersonatedUser = newId.Impersonate();
 }
开发者ID:ipduncan,项目名称:Refactor,代码行数:7,代码来源:Impersonation.cs

示例8: impersonateValidUser

        //public void Page_Load(Object s, EventArgs e)
        //{
        //    if (impersonateValidUser("username", "domain", "password"))
        //    {
        //        //Insert your code that runs under the security context of a specific user here.
        //        undoImpersonation();
        //    }
        //    else
        //    {
        //        //Your impersonation failed. Therefore, include a fail-safe mechanism here.
        //    }
        //}

        /// <summary>
        /// 模擬使用者
        /// </summary>
        /// <param name="userName">使用者名稱</param>
        /// <param name="domain">網域名稱</param>
        /// <param name="password">密碼</param>
        /// <returns>True:模擬成功;False:模擬失敗</returns>
        public static bool impersonateValidUser(String userName, 
                                                String domain, 
                                                String password
                                                )
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }
开发者ID:ChiangHanLung,项目名称:PIC_VDS,代码行数:53,代码来源:Impersonate.cs

示例9: PerformanceCounterRetriever

        public PerformanceCounterRetriever(string server, string domain, string user, string password)
        {
            if (string.IsNullOrWhiteSpace(server))
                throw new ArgumentException($"Null/blank {nameof(server)} specified");
            if (string.IsNullOrWhiteSpace(domain))
                throw new ArgumentException($"Null/blank {nameof(domain)} specified");
            if (string.IsNullOrWhiteSpace(user))
                throw new ArgumentException($"Null/blank {nameof(user)} specified");
            if (password == null)
                throw new ArgumentNullException(nameof(password));

            try
            {
                var userHandle = new IntPtr(0);
                var logonSuccess = LogonUser(user, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref userHandle);
                if (!logonSuccess)
                    throw new Exception("LogonUser failed");
                _identity = new WindowsIdentity(userHandle);
                _context = _identity.Impersonate();
                _server = server;
                _disposed = false;
            }
            finally
            {
                Dispose();
            }
        }
开发者ID:zhangz,项目名称:Toolbox,代码行数:27,代码来源:PerformanceCounterRetriever.cs

示例10: Impersonate

        public void Impersonate(string domainName, string userName, string password)
        {
            try
            {
                const int logon32ProviderDefault = 0;
                const int logon32LogonInteractive = 2;
                TokenHandle = IntPtr.Zero;
                var returnValue = LogonUser(
                                    userName,
                                    domainName,
                                    password,
                                    logon32LogonInteractive,
                                    logon32ProviderDefault,
                                    ref TokenHandle);

                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser call failed with error code : " + ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                NewId = new WindowsIdentity(TokenHandle);
                ImpersonatedUser = NewId.Impersonate();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred. " + ex.Message);
            }
        }
开发者ID:JonasSyrstad,项目名称:Stardust,代码行数:29,代码来源:ImpersonateUser.cs

示例11: Impersonate

        /// <summary>
        /// 模擬特定使用者帳號
        /// 
        /// reference : http://www.dotblogs.com.tw/puma/archive/2009/02/24/7281.aspx
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>表示模擬作業前的 Windows 使用者</returns>
        /// <remarks>
        /// Response.Write("CurrentUserName: " + WindowsIdentity.GetCurrent().Name);
        /// 
        /// 模擬使用者
        /// WindowsImpersonationContext wic = Impersonate("localhost", "Administrator", "AccountPass");
        /// Response.Write("CurrentUserName: " + WindowsIdentity.GetCurrent().Name);
        /// 
        /// 取消模擬
        /// wic.Undo();
        /// Response.Write("CurrentUserName: " + WindowsIdentity.GetCurrent().Name);
        /// </remarks>
        public WindowsImpersonationContext Impersonate(string domain, string userName, string password)
        {
            WindowsImpersonationContext impersonationContext = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                        LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                    }
                }
            }
            catch
            {
                ;
            }
            finally
            {
                if (token != IntPtr.Zero)
                    CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    CloseHandle(tokenDuplicate);
            }

            return impersonationContext;
        }
开发者ID:skt90u,项目名称:skt90u-framework-dotnet,代码行数:55,代码来源:ExtWindowsIdentity.cs

示例12: DeleteHomeDirectory

        /// <summary>
        /// removes the old home folder directory and contents.
        /// </summary>
        /// <param name="strSource">source location of old home folder to remove</param>
        public void DeleteHomeDirectory(string strSource)
        {
            IntPtr admin_token = default(IntPtr);
            WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
            WindowsIdentity wid_admin = null;
            WindowsImpersonationContext wic = null;
            if (LogonUser(Form1._AdminUser, Form1._Domain, Form1._Password, 9, 0, ref admin_token) != 0)
            {
                wid_admin = new WindowsIdentity(admin_token);
                wic = wid_admin.Impersonate();

                try
                {
                    Directory.Delete(strSource, true);
                    Form1.myForm.cbMoveHome.Checked = true;
                    Form1.myForm._Notes.AppendLine();
                    Form1.myForm._Notes.Append("<br>Home folder moved to backup location.<br>");
                }
                catch (Exception ex)
                {
                    Form1.myForm.lblMessage.Text = ex.Message;
                    Form1.myForm.cbMoveHome.Checked = false;
                    Form1.myForm._Notes.AppendLine();
                    Form1.myForm._Notes.Append("<br><b>Error in home folder move process.</b><br>" + ex.Message + "<br>");
                }
            }
        }
开发者ID:KameronHott,项目名称:Work,代码行数:31,代码来源:HomeFolder.cs

示例13: Enter

        public void Enter()
        {
            if (this.IsInContext)
            {
                return;
            }

            this.token = new IntPtr(0);
            try
            {
                this.token = IntPtr.Zero;
                bool logonSuccessfull = NativeMethods.LogonUser(
                   this.username,
                   this.domain,
                   this.password,
                   Logon32LogonInteractive,
                   Logon32ProviderDefault,
                   ref this.token);
                if (logonSuccessfull == false)
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }

                var identity = new WindowsIdentity(this.token);
                this.context = identity.Impersonate();
            }
            catch
            {
                // Catch exceptions here
            }
        }
开发者ID:romanpeshterski,项目名称:OpenJudgeSystem,代码行数:32,代码来源:WrapperImpersonationContext.cs

示例14: btnRun_Click

        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                IntPtr hToken = IntPtr.Zero;
                IntPtr hTokenDuplicate = IntPtr.Zero;

                if (NativeMethods.LogonUser(txtUsername.Text, txtDomain.Text, txtPassword.Text, (uint)NativeMethods.LogonType.LOGON32_LOGON_INTERACTIVE, (uint)NativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT, out hToken))
                {
                    if (NativeMethods.DuplicateToken(hToken, 2, ref hTokenDuplicate))
                    {
                        WindowsIdentity windowsIdentity = new WindowsIdentity(hTokenDuplicate);
                        using (WindowsImpersonationContext impersonationContext = windowsIdentity.Impersonate())
                        {
                            System.Diagnostics.Debug.WriteLine(WindowsIdentity.GetCurrent().Name);

                            MessageBox.Show(this, string.Format("Ready to execute program {0} as {1}\\{2}...", txtProgram.Text, txtDomain.Text, txtUsername.Text), "Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            impersonationContext.Undo();
                        }
                    }
                }
                else
                {
                    MessageBox.Show(this, string.Format("Authentication failed for {0}\\{1}.", txtDomain.Text, txtUsername.Text), "Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                if (hToken != IntPtr.Zero) NativeMethods.CloseHandle(hToken);
                if (hTokenDuplicate != IntPtr.Zero) NativeMethods.CloseHandle(hTokenDuplicate);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, string.Format("An error occurred: {0}", ex), "Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
开发者ID:SamuelMorel,项目名称:CS.NET,代码行数:35,代码来源:LoginForm.cs

示例15: Impersonate

 /// <summary>
 /// Starts the impersonation.
 /// </summary>
 public void Impersonate()
 {
     // Create Identity.
     WindowsIdentity newId = new WindowsIdentity(this.tokenHandle);
     
     // Start impersonating.
     this.impersonatedUser = newId.Impersonate();
 }
开发者ID:BiYiTuan,项目名称:CruiseControl.NET,代码行数:11,代码来源:Impersonation.cs


注:本文中的System.Security.Principal.WindowsIdentity.Impersonate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。