简体   繁体   English

使用C#从ASP.Net MVC访问Active Directory

[英]Accessing Active Directory from ASP.Net MVC using C#

I need to access Active Directory to get information about groups that customers belong to. 我需要访问Active Directory以获取有关客户所属组的信息。 The project I have is an ASP.Net MVC application using C#. 我的项目是使用C#的ASP.Net MVC应用程序。 I've never programmed against Active Directory before, and need some advice on what the best way to get started is, what security model to use to access the information, and maybe point me to some good tutorials. 我之前从未编写过针对Active Directory的编程,并且需要一些关于最佳入门方式的建议,使用什么安全模型来访问信息,并且可能指向一些好的教程。

Since you're using MVC, you have access to the new System.DirectoryServices.AccountManagement namespace in .NET 3.5. 由于您正在使用MVC,因此您可以访问.NET 3.5中的新System.DirectoryServices.AccountManagement命名空间。 These classes should be preferred over the older classes in DirectoryServices itself as they are much simpler to use. 这些类应该优先于DirectoryServices本身的旧类,因为它们使用起来要简单得多。 There are a couple of gotchas that haven't been solved in 3.5 (1500 member limit when querying groups, for instance), but I'm assured that these have been fixed in .NET 4.0. 有一些问题在3.5中没有解决(例如,在查询组时有1500个成员限制),但我确信这些已在.NET 4.0中得到修复。 For most tasks, the new classes work very well. 对于大多数任务,新类非常有效。

 using (var context = new PrincipalContext( ContextType.Domain )) 
 {
      using (var user = UserPrincipal.FindByIdentity( context, "username" ))
      {
          var groups = user.GetAuthorizationGroups();
          ...
      }
 }

Use System.DirectoryServices namespace to access the AD. 使用System.DirectoryServices命名空间访问AD。

The two most important classes are: 两个最重要的课程是:

  1. DirectoryEntry ; DirectoryEntry ;
  2. DirectorySearcher . DirectorySearcher

Let's suppose that your domain is: MyIntranet.MyCompany.com 假设您的域名是: MyIntranet.MyCompany.com

Then, you will have to create a root instance of the DirectoryEntry class: 然后,您将必须创建DirectoryEntry类的根实例:

DirectoryEntry root = new DirectoryEntry("LDAP://DC=MyIntranet,DC=MyCompany,DC=com");

When searching the AD for a particular occurence of a group or user: 在AD中搜索组或用户的特定出现时:

DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchRoot = root;
searcher.SearchScope = SearchScope.Subtree;

Let's say you want to look for a username named: AnyUser1 , the DirectorySearcher.Filter should look like: 假设您要查找名为AnyUser1的用户名,DirectorySearcher.Filter应如下所示:

searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0})", "AnyUser1");

Then, get the result through the SearchResult class as follows: 然后,通过SearchResult类获取结果,如下所示:

bool userFound = false;
SearchResult foundUser = null;

try {
    foundUser = searcher.FindOne(); // You might as well use the FindAll() method if you expect more then one result.
    userFound = foundUser != null;
} catch(Exception) {
    throw;
}

if (!userFound)
    return;

DirectoryEntry user = foundUser.GetDirectoryEntry();

Then, you may get the groups which this user is member of like so through the memberOf property: 然后,您可以通过memberOf属性获取此用户所属的组:

user.Properties("memberOf").Value

For a good overview, see this CodeProject article: How to (almost) everything in Active Directory . 有关概述,请参阅此CodeProject文章: 如何(几乎)在Active Directory中的所有内容

And ofr a list of the properties: Mapping Between IADsUser Properties and Active Directory Attributes . 还有一个属性列表: IADsUser属性和Active Directory属性之间的映射

EDIT #1 编辑#1

If you're using impersonation, you might perhaps consider setting some parameters to your application such as DefaultRootDomain , DefaultUserName and DefaultPassword , then use them when instantiating your root DirectoroEntry . 如果您正在使用模拟,您可能会考虑为应用程序设置一些参数,例如DefaultRootDomainDefaultUserNameDefaultPassword ,然后在实例化根DirectoroEntry时使用它们。

public static class AdHelper {

    public static string DefaultRootDse {
        get {
            return Properties.Settings.Default.DefaultRootDomain;
        }
    }

    private static string DefaultUserName {
        get {
            return Properties.Settings.Default.DefaultUserName;
        }
    }

    private static string DefaultPassword {
        get {
            return Properties.Settings.Default.DefaultPassword;
        }
    } 

    public static DirectoryEntry RootDse {
        get {
            if (_rootDse == null)
                _rootDse = new DirectoryEntry(DefaultRootDse, DefaultUserName, DefaultPassword);
            return _rootDse;
        }
    }
    private static DirectoryEntry _rootDse;
}

If you have .NET 3.5 or if you can upgrade to it - by all means use the new feature in System.DirectoryServices.AccountManagement ! 如果你有.NET 3.5或者你可以升级到它 - 请System.DirectoryServices.AccountManagement使用System.DirectoryServices.AccountManagement的新功能!

See a great intro article Managing Directory Security Principals in the .NET Framework 3.5 on MSDN Magazine for more information and a jumpstart. 有关更多信息和快速入门,请参阅MSDN杂志上.NET Framework 3.5中的管理目录安全主体的精彩介绍文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM