从UserPrincipal获取WindowsPrincipal

时间:2016-02-08 17:09:59

标签: c# .net windows security userprincipal

目标

我正在编写一个抽象各种Windows用户机制的类。我的班级知道用户的帐户名称和域名(如果有的话)。我试图水合一个属性,指示用户是否对域所属的域或本地环境具有管理权限。

问题

WindowsPrincipal类通过IsInRole提供该信息,但它的构造函数需要WindowsIdentity,我找不到在没有用户主体名称(UPN)的情况下建立的方法。 UserPrincipal.UserPrincipalName属性可供域用户使用,但对本地用户为null。还有另一种方法可以从WindowsPrincipal获得UserPrincipal吗?或者,有没有另一种方法可以在没有它的情况下实现目标?

来源

using (PrincipalContext principalContext = new PrincipalContext(PrincipalContextType, principalContextName))
{
    using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, Name))
    {
        // Capture additional information from the user principal.
        Certificates = userPrincipal.Certificates;
        DisplayName = userPrincipal.DisplayName;
        UserPrincipalName = userPrincipal.UserPrincipalName;

        // This constructor blows up because UserPrincipalName is null for local users.
        using (WindowsIdentity windowsIdentity = new WindowsIdentity(UserPrincipalName))
        {
            // Capture group membership information about the specified user.
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

            // Determine if the user has administrative privilege on the domain or local machine.
            HasAdministrativePrivilege = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
        }
    }
}

提前致谢。

0 个答案:

没有答案
相关问题