如何从DOMAIN\user格式的用户名创建的WindowsIdentity / WindowsPrincipal [英] How to create WindowsIdentity/WindowsPrincipal from username in DOMAIN\user format

查看:2651
本文介绍了如何从DOMAIN\user格式的用户名创建的WindowsIdentity / WindowsPrincipal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的WindowsIdentity(串)构造函数需要的用户名是在 username@domain.com 格式。但在我的情况下,我从一个数据库用户名老 DOMAIN\user 格式(然后要检查他们的Windows角色成员)。

The WindowsIdentity(string) constructor requires the username to be in username@domain.com format. But in my case I get the usernames from a DB in the old DOMAIN\user format (and then have to check their Windows role membership).

什么是创建 WindowsPrincipal 从旧风格的用户名?

What is the best way of creating WindowsPrincipal from the old style username?

推荐答案

这似乎并没有转换的用户名格式不涉及查询到Active Directory的方式。因为是这样的话,没有必要创建 WindowsPrincipal 用于检查组成员,因为这很可能需要到AD又一连接

It does seem that there is no way of converting the username format without involving a query to Active Directory. Since that is the case there is no need to create WindowsPrincipal for checking the group membership since that would probably need yet another connection to AD.

通过使用 System.DirectoryServices.AccountManagement 命名空间,你既可以得到用户的UPN和检查组成员。

By using the System.DirectoryServices.AccountManagement namespace you can both get the UPN of the user and check the group membership.

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;
    }
}

这篇关于如何从DOMAIN\user格式的用户名创建的WindowsIdentity / WindowsPrincipal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆