我需要找出我的 windows currentuser 是域用户还是本地用户?我得到了我的 CurrentPrincipal :
System.Threading.Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
我需要找出我的 windows currentuser 是域用户还是本地用户?我得到了我的 CurrentPrincipal :
System.Threading.Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
通常,Windows 非域用户没有 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 遍历机器的所有加入域,并查找用户是否在我们迭代的任何域中。
我没有可供我使用的广告,但我希望这可能会奏效:
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;
}