如何确定我的 Windows 用户是域用户

本文关键字:用户 Windows 何确定 我的 | 更新日期: 2023-09-27 18:36:36

我需要找出我的Windows currentuser是域用户还是本地用户?我得到我的当前校长是这样的:

 System.Threading.Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

如何确定我的 Windows 用户是域用户

通常,Windows NON 域用户没有 UPN 名称。像下面如果我用/upn 解雇 WHOAMI:

C:'>WHOAMI /UPN
ERROR: Unable to get User Principal Name (UPN) as the current logged-on user
       is not a domain user.

基于此,使用以下代码,我们可以找到用户是否是域用户。

 var upnName = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;
    if (upnName == null)
    {
        //not a domain user
    }

另一种冗长的方法是获取SAM格式的用户名。然后使用 DirectoryEntry、DirectorySearcher 和其他 AD API 遍历计算机的所有已加入域,并查找用户是否位于我们迭代的任何域中。

查找计算机 ex1 和 ex2 的所有域

以下是如何在 C# 中从 Active Directory 获取域用户信息

我没有 AD 可供我使用,但我希望这可能会起作用:

public bool IsDomainUser()
{
  bool isDomain = false; 
  foreach (var grp in WindowsIdentity.GetCurrent().Groups)
  {
      if (grp.IsValidTargetType(typeof(SecurityIdentifier)))
      {
        SecurityIdentifier si = 
                (SecurityIdentifier)grp.Translate(typeof(SecurityIdentifier));
        // not sure if this is right, but I'm not in a domain and don't have this SID
        // I do have LocalSID however, so you might need to turn it around,
        // if you have LocalSid you are not using a domain acount
        if (si.IsWellKnown(WellKnownSidType.BuiltinDomainSid))
        {
            isDomain = true;
        }
      }
   }
   return isDomain;
 }

   // for debugging list SIDS for current user and its groups
   foreach (var obj in Enum.GetValues(typeof(WellKnownSidType)))
   {
    if (WindowsIdentity.GetCurrent().User.IsWellKnown((WellKnownSidType)obj))
    {
        Debug.WriteLine("User:" + obj.ToString());
    }
    foreach (var grp in WindowsIdentity.GetCurrent().Groups)
    {
        if (grp.IsValidTargetType(typeof(SecurityIdentifier)))
        {
            SecurityIdentifier si = 
                 (SecurityIdentifier) grp.Translate(typeof(SecurityIdentifier));
            if (si.IsWellKnown((WellKnownSidType)obj))
            {
                Debug.WriteLine("Grp: " + grp.ToString() + " : " + obj.ToString());
            }
        }
    }
  }
using System.DirectoryServices.AccountManagement;
bool IsDomainUser()
{
    return UserPrincipal.Current.ContextType == ContextType.Domain;
}