首先我将一一回答你的问题,
LDAP 上的用户与 DB 上的用户相同,您可以在用户表中保存 LDAP 的用户名及其域,
但 LDAP 上的配置文件可能会因您的配置文件表而异,但可以从 LDAP 地址获取。
通过 LDAP 检查用户名和密码就足够了,只需将 LDAP 地址保存在一个表中(例如 ExternalPath),并在 User 和 ExternalPath 表之间建立关系。 LDAP 地址包含一些规范。
是的,您必须有一个单独的机制来识别 LDAP 用户,我将进一步解释。
如果一切都是原子的并且设计正确,这并不难,在进一步的步骤中您可能会发现它很容易。
让我谈谈我在 LDAP 方面的经验,并在 LDAP 和 DB 上验证用户以及我们的架构。
我实现了一个名为 Auth.svc 的 WCF 服务,该服务包含一个名为 AuthenticateAndAuthorizeUser 的方法,这对于来自 LDAP 或任何地方的用户是透明的。
我希望您通过以下步骤获得通过 LDAP 和 DB 验证用户的线索和架构:
1- 首先,我有一个名为 Users 的表,其中包含用户信息和另一个名为 ExternalPath 的字段作为外键,如果它为空,则指定 UserName 在数据库中,否则为密码来自UserDirectory。
2-在第二步中,您必须保存 LDAP 地址(在我的情况下,LDAP 地址在 ExternalPath 表中),所有 LDAP 地址通常都在端口 389 上。
3- 实施验证用户,如果未找到(使用用户名和密码),则检查它的 ExternalPath 以通过 LDAP 地址进行验证。
4- DB 架构应该类似于下面的屏幕截图。
如您所见,ExternalPath 字段指定用户是否来自 LDAP。
5-在表示层中,我也在定义 LDAP 服务器,如下图所示
6- 另一方面,在系统中添加新用户时,您可以为用户定义 LDAP,在我的情况下,我在添加用户表单中的下拉列表中列出 LDAP 标题(如果管理员选择LDAP 地址则不需要获取密码并将其保存在数据库中),正如我提到的,只需要保存 LDAP 用户名而不是密码。
7-但最后一件事是在 LDAP 和 DB 上验证用户。
所以认证方法是这样的:
User userLogin = User.Login<User>(username, password, ConnectionString, LogFile);
if (userLogin != null)
return InitiateToken(userLogin, sourceApp, sourceAddress, userIpAddress);
else//Check it's LDAP path
{
User user = new User(ConnectionString, LogFile).GetUser(username);
if (user != null && user.ExternalPath != null)
{
LDAPSpecification spec = new LDAPSpecification
{
UserName = username,
Password = password,
Path = user.ExternalPath.Path,
Domain = user.ExternalPath.Domain
};
bool isAthenticatedOnLDAP = LDAPAuthenticateUser(spec);
}
}
如果 userLogin 通过输入的用户名和密码在 DB 中不存在,那么我们应该通过相关的 LDAP 地址对其进行身份验证。
在else 块中从用户表中查找用户并获取它的ExternalPath,如果此字段不为空则表示用户在 LDAP 上。
8- LDAPAuthenticateUser 方法是:
public bool LDAPAuthenticateUser(LDAPSpecification spec)
{
string pathDomain = string.Format("LDAP://{0}", spec.Path);
if (!string.IsNullOrEmpty(spec.Domain))
pathDomain += string.Format("/{0}", spec.Domain);
DirectoryEntry entry = new DirectoryEntry(pathDomain, spec.UserName, spec.Password, AuthenticationTypes.Secure);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + spec.UserName + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
}
catch (Exception ex)
{
Logging.Log(LoggingMode.Error, "Error authenticating user on LDAP , PATH:{0} , UserName:{1}, EXP:{2}", pathDomain, spec.UserName, ex.ToString());
return false;
}
return true;
}
如果在LDAPAuthenticateUser 中引发异常意味着用户在用户目录中不存在。
身份验证代码接受域、用户名、密码和 Active Directory 中树的路径。
上述代码使用 LDAP 目录提供程序,身份验证方法调用 LDAPAuthenticateUser 并传入从用户那里收集的凭据。然后,使用目录树的路径、用户名和密码创建一个 DirectoryEntry 对象。 DirectoryEntry 对象试图通过获取NativeObject 属性来强制绑定AdsObject。如果成功,则通过创建DirectorySearcher 对象并通过过滤SAMAccountName 来获得用户的CN 属性。在用户通过身份验证并且未发生异常后,方法返回 true 表示用户在给定的 LDAP 地址上找到。
要查看有关轻量级目录访问协议的更多信息并对其进行身份验证,THIS Link 可能很有用,它可以详细说明规范。
希望对您有所帮助。