c# - 如何从 DOMAIN\user 格式的用户名创建 WindowsIdentity/WindowsPrincipal

标签 c# windows-identity windows-principal

WindowsIdentity(string) 构造函数要求用户名采用 username@domain.com 格式。但在我的例子中,我从旧的 DOMAIN\user 格式的数据库中获取用户名(然后必须检查他们的 Windows 角色成员身份)。

从旧式 (sAMAccountName) 用户名​​创建 WindowsPrincipal 的最佳方法是什么?

最佳答案

似乎没有办法在不涉及对 Active Directory 的查询的情况下转换用户名格式。由于是这种情况,因此无需创建 WindowsPrincipal 来检查组成员身份,因为这可能需要与 AD 的另一个连接。

通过使用 System.DirectoryServices.AccountManagement 命名空间,您可以获得用户的 UPN 并检查组成员身份。

string accountName = @"DOMAIN\user";
var groupNames = new[] { "DOMAIN\Domain Users", "DOMAIN\Group2" }; // the groups that we need to verify if the user is member of

// cannot create WindowsIdentity because it requires username in form user@domain.com but the passed value will be DOMAIN\user.
using (var pc = new PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, Environment.UserDomainName))
{
    using (var p = UserPrincipal.FindByIdentity(pc, accountName))
    {
        // if the account does not exist or is not an user account
        if (p == null)
            return new string[0];

        // if you need just the UPN of the user, you can use this
        ////return p.UserPrincipalName;

        // find all groups the user is member of (the check is recursive).
        // Guid != null check is intended to remove all built-in objects that are not really AD gorups.
        // the Sid.Translate method gets the DOMAIN\Group name format.
        var userIsMemberOf = p.GetAuthorizationGroups().Where(o => o.Guid != null).Select(o => o.Sid.Translate(typeof(NTAccount)).ToString());

        // use a HashSet to find the group the user is member of.
        var groups = new HashSet<string>(userIsMemberOf, StringComparer.OrdinalIgnoreCase);
        groups.IntersectWith(groupNames);

        return groups;
    }
}

关于c# - 如何从 DOMAIN\user 格式的用户名创建 WindowsIdentity/WindowsPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835134/

相关文章:

c# - 模拟在 Powershell 中使用 WindowsIdentity 抛出 FileNotFoundException

c# - 如何触发 Windows 的用户凭据提示?

c# - WindowsPrincipal.IsInRole 和通用与全局事件目录组

c# - 如何编写 .Net UDP 可扩展服务器

c# - 使用依赖注入(inject)的开销

c# - 从 ASP.NET 页面中获取 Windows 登录

c# - 如何确保 IsInRole 检查不使用缓存的凭据

c# - 从 c++11 time_t 创建一个可转换为 .net DateTime 的字符串

c# - 如何删除每个响应上的一些 httpresponse header (例如 Server 和 ETag)?