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


C# Principal.WindowsIdentity类代码示例

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


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

示例1: 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

示例2: GetProcessWindowsIdentity

        public static WindowsIdentity GetProcessWindowsIdentity(Process process)
        {
            IntPtr tokenHandle = IntPtr.Zero;
            WindowsIdentity wi = null;
            try
            {
                tokenHandle = GetProcessTokenHandle(process);
                wi = new WindowsIdentity(tokenHandle);
            }
            catch
            {
                if (wi != null)
                {
                    wi.Dispose();
                }

                return null;
            }
            finally
            {
                if (tokenHandle != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(tokenHandle);
                }
            }

            return wi;
        }
开发者ID:UhuruSoftware,项目名称:vcap-dotnet,代码行数:28,代码来源:ProcessUser.cs

示例3: GetUpnFromWindowsIdentity

        string GetUpnFromWindowsIdentity(WindowsIdentity windowsIdentity)
        {
            string downlevelName = null;
            string upnName = null;
 
            try
            {
                downlevelName = windowsIdentity.Name;
 
                if (IsMachineJoinedToDomain())
                {
                    upnName = GetUpnFromDownlevelName(downlevelName);
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
             }
 
            // if the AD cannot be queried for the fully qualified domain name,
            // fall back to the downlevel UPN name
            return upnName ?? downlevelName;
        }
开发者ID:roncain,项目名称:wcf,代码行数:26,代码来源:UpnEndpointIdentity.cs

示例4: WindowsPrincipal

        public WindowsPrincipal (WindowsIdentity ntIdentity) {
            if (ntIdentity == null)
                throw new ArgumentNullException("ntIdentity"); 
            Contract.EndContractBlock();
 
            m_identity = ntIdentity; 
        }
开发者ID:sjyanxin,项目名称:WPFSource,代码行数:7,代码来源:WindowsPrincipal.cs

示例5: GetUpnFromWindowsIdentity

        string GetUpnFromWindowsIdentity(WindowsIdentity windowsIdentity)
        {
            string downlevelName = null;
            string upnName = null;

            try
            {
                downlevelName = windowsIdentity.Name;

                if (this.IsMachineJoinedToDomain())
                {
                    upnName = GetUpnFromDownlevelName(downlevelName);
                }
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
            }

            // if the AD cannot be queried for the fully qualified domain name,
            // fall back to the downlevel UPN name
            return upnName ?? downlevelName;
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:29,代码来源:UpnEndpointIdentity.cs

示例6: CheckUserGroup

 public static bool CheckUserGroup(string userName, string userGroup)
 {
     var wi = new WindowsIdentity(userName);
     var wp = new WindowsPrincipal(wi);
     bool inRole = wp.IsInRole(userGroup);
     return inRole;
 }
开发者ID:dcanessa,项目名称:Proyecto-Boston,代码行数:7,代码来源:LdapAuthentication.cs

示例7: 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

示例8: AutoWebProxyScriptEngine

        internal AutoWebProxyScriptEngine(WebProxy proxy, bool useRegistry)
        {
            GlobalLog.Assert(proxy != null, "'proxy' must be assigned.");
            webProxy = proxy;
            m_UseRegistry = useRegistry;

#if !FEATURE_PAL
            m_AutoDetector = AutoDetector.CurrentAutoDetector;
            m_NetworkChangeStatus = m_AutoDetector.NetworkChangeStatus;

            SafeRegistryHandle.RegOpenCurrentUser(UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out hkcu);
            if (m_UseRegistry)
            {
                ListenForRegistry();

                // Keep track of the identity we used to read the registry, in case we need to read it again later.
                m_Identity = WindowsIdentity.GetCurrent();
            }

#endif // !FEATURE_PAL

            // In Win2003 winhttp added a Windows Service handling the auto-proxy discovery. In XP using winhttp
            // APIs will load, compile and execute the wpad file in-process. This will also load COM, since
            // WinHttp requires COM to compile the file. For these reasons, we don't use WinHttp on XP, but
            // only on newer OS versions where the "WinHTTP Web Proxy Auto-Discovery Service" exists.
            webProxyFinder = new HybridWebProxyFinder(this);
        }
开发者ID:uQr,项目名称:referencesource,代码行数:27,代码来源:_AutoWebProxyScriptEngine.cs

示例9: 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

示例10: 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

示例11: 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

示例12: PerformActionRemotely

        // This method is used to perform action delegate remotely on CIFS Share
        public static void PerformActionRemotely(Action action, ServerConnectionCredentials serverCreds)
        {
            WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
            WindowsImpersonationContext wic = null;
            try
            {
                IntPtr admin_token = new IntPtr();
                if (LogonUser(serverCreds.Username, ".", serverCreds.Password, 9, 0, ref admin_token) != 0)
                {
                    wic = new WindowsIdentity(admin_token).Impersonate();

                    action();
                }
            }
            catch (Exception se)
            {
                int ret = Marshal.GetLastWin32Error();
                Logger.LogError("Invoking action on remote machine failed with Error code " + ret.ToString(), serverCreds.IP, se);
                return;
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
开发者ID:asirko-softheme,项目名称:DDTGenerator,代码行数:29,代码来源:HelperMethods.cs

示例13: 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

示例14: GetHashedRoles

 private static HashSet<string> GetHashedRoles(WindowsIdentity id)
 {
     lock (s_Lock)
     {
         HashSet<string> result;
         if (!s_RoleCache.TryGetValue(id.Name, out result))
         {
             result = new HashSet<string>();
             if (id.Groups != null)
             {
                 IdentityReferenceCollection identityReferenceCollection = id.Groups.Translate(typeof(NTAccount));
                 if (identityReferenceCollection != null)
                 {
                     IEnumerable<string> groups =
                         identityReferenceCollection
                             .AsEnumerable()
                             .Select(x => x.Value);
                     foreach (string @group in groups)
                     {
                         string[] items = @group.Split('\\');
                         result.Add(items.Length != 2 ? @group : items[1]);
                     }
                 }
             }
             s_RoleCache.Add(id.Name, result);
         }
         return result;
     }
 }
开发者ID:jandppw,项目名称:ppwcode-recovered-from-google-code,代码行数:29,代码来源:CustomPrincipal.cs

示例15: ProcessIdentity

 protected override void ProcessIdentity(WindowsIdentity identity)
 {
     using (var hToken = new SafeTokenHandle(identity.Token, false))
     {
         Utils.AdjustTokenPrivileges(hToken, Privileges);
     }
 }
开发者ID:razaraz,项目名称:Pscx,代码行数:7,代码来源:SetPrivilegeCommand.cs


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