如何以DOMAIN\user格式的用户名创建WindowsIdentity/WindowsPrincipal

Kna*_*ģis 17 c# windows-principal windows-identity

WindowsIdentity(string)构造函数需要的用户名是在username@domain.com格式.但在我的情况下,我以旧DOMAIN\user格式从数据库中获取用户名(然后必须检查其Windows角色成员身份).

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

Kna*_*ģis 14

似乎没有办法转换用户名格式而不涉及到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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 哪个.NET框架版本?和组装?哪个是AccountManagement,PrincipalContext,UserPrincipal,StringComparer类? (7认同)

Dan*_*con 10

这工作正常,但涉及查询活动目录/ SAM存储(取决于上下文)...

private WindowsIdentity GetWindowsIdentity(
  string userName)
{
  using (var user =
    UserPrincipal.FindByIdentity(
      UserPrincipal.Current.Context,
      IdentityType.SamAccountName,
      userName
      ) ??
    UserPrincipal.FindByIdentity(
      UserPrincipal.Current.Context,
      IdentityType.UserPrincipalName,
      userName
      ))
  {
    return user == null
      ? null
      : new WindowsIdentity(user.UserPrincipalName);
  }
}
Run Code Online (Sandbox Code Playgroud)