如何获取授权用户的Active Directory组ID

时间:2013-03-01 12:58:50

标签: asp.net-mvc c#-4.0 active-directory

我的Web应用程序使用Authorize属性并指定了角色来限制对某些页面的访问:

[Authorize(Roles = "AD_group1, AD_group2")]

问题是 - 有没有办法可以为授权用户获取某种Active Directory groupId(无论是int还是字符串)?

UPD: 基本思想是将一些表存储在数据库中,其中包含应为每个组分开的模板。例如group1中的用户可以使用一些模板来快速回答典型问题,而group2没有任何模板,或者有其他模板

1 个答案:

答案 0 :(得分:3)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // find a user
   UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
   // or if you want the currently logged in user - you can also use:
   // UserPrincipal user = UserPrincipal.Current;

   if(user != null)
   {
       // get all groups the user is a member of
       foreach(GroupPrincipal group in user.GetAuthorizationGroups())
       {
           string distinguishedName = group.DistinguishedName;
           Guid groupGuid = group.Guid;
       }
   }
}

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!