• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Principal.WindowsIdentity类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


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


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


示例18: ProcessIdentity

        protected override void ProcessIdentity(WindowsIdentity identity)
        {
            bool result = true;

            if (this.ParameterSetName == PARAMSET_NAME)
            {
                if (!TranslateGroupNames())
                {
                    result = false;
                }
            }

            if (result)
            {
                foreach (var reference in _references)
                {
                    // ReSharper disable PossibleNullReferenceException
                    if (!identity.Groups.Contains(reference))
                    // ReSharper restore PossibleNullReferenceException
                    {
                        result = false;
                        break;
                    }
                }
            }
            WriteObject(result);
        }
开发者ID:nickchal,项目名称:pash,代码行数:27,代码来源:TestUserGroupMembershipCommand.cs


示例19: CheckUserRights

            public static bool CheckUserRights(string userLogin, string rightName)
            {
                string programName = WebConfigurationManager.AppSettings["progName"];
                bool flag = false;

                SqlParameter pProgramName = new SqlParameter() { ParameterName = "program_name", Value = programName, DbType = DbType.AnsiString };
                SqlParameter pRightName = new SqlParameter() { ParameterName = "sys_name", Value = rightName, DbType = DbType.AnsiString };

                DataTable dt = new DataTable();

                dt = ExecuteQueryStoredProcedure(sp, "getUserGroupSid", pProgramName, pRightName);

                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];

                    string sid = dr["sid"].ToString();

                    try
                    {
                        WindowsIdentity wi = new WindowsIdentity(userLogin);
                        WindowsPrincipal wp = new WindowsPrincipal(wi);
                        SecurityIdentifier grpSid = new SecurityIdentifier(sid);

                        flag = wp.IsInRole(grpSid);
                    }
                    catch (Exception ex)
                    {
                        flag = false;
                    }
                }

                return flag;
            }
开发者ID:WakeDown,项目名称:ServicePlaning,代码行数:34,代码来源:Db.Users.cs


示例20: login_Using_WindowsAuthentication

        public Guid login_Using_WindowsAuthentication(WindowsIdentity identity)
        {
            var userName = "";
            if (identity != null && identity.IsAuthenticated && identity.ImpersonationLevel == TokenImpersonationLevel.Impersonation)
                userName = identity.Name;
            else
            {
                // not sure how to test the one bellow since it needs a valid HttpContext
                userName = HttpContextFactory.Current.field("_context")
                                             .field("_wr")
                                             .invoke("GetServerVariable", "LOGON_USER") as string;
            }

            if (userName.valid())
            {
                var tmUser = userName.tmUser();
                if(tmUser.isNull())
                {
                    TM_UserData.Current.logTBotActivity("Windows Authentication", "Creating User: {0}".format(userName));
                    tmUser = userName.newUser().tmUser();
                }
                if (tmUser.GroupID != (int)calculateUserGroupBasedOnWindowsIdentity(identity))
                {
                    tmUser.GroupID = (int)calculateUserGroupBasedOnWindowsIdentity(identity);
                    tmUser.save();
                    TM_UserData.Current.logTBotActivity("Windows Authentication", "Created session for User: {0}".format(userName));
                }
                return tmUser.login("WindowsAuth");
            }
            return Guid.Empty;
        }
开发者ID:TeamMentor,项目名称:Dev,代码行数:31,代码来源:WindowsAuthentication.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Principal.WindowsImpersonationContext类代码示例发布时间:2022-05-26
下一篇:
C# Principal.SecurityIdentifier类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap