本文主要介绍ASP.NET Core 2.0中,实现 LDAP Active Directory(活动目录)的身份验证的方法及相关示例代码。

1、安装引用Microsoft.Windows.Compatibility

相关文档:Windows Compatibility Pack

Install-Package Microsoft.Windows.Compatibility 

2、LDAP验证示例代码

const string LDAP_PATH = "EX://exldap.example.com:5555";
const string LDAP_DOMAIN = "exldap.example.com:5555";
using (var context = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN, "service_acct_user", "service_acct_pswd")) {
    if (context.ValidateCredentials(username, password)) {
        using (var de = new DirectoryEntry(LDAP_PATH))
        using (var ds = new DirectorySearcher(de)) {
            // 验证用户拥有正确权限的其他逻辑
            // 用户认证和授权
            var identities = new List<ClaimsIdentity> { new ClaimsIdentity("custom auth type") };
            var ticket = new AuthenticationTicket(new ClaimsPrincipal(identities), Options.Scheme);
            return Task.FromResult(AuthenticateResult.Success(ticket));
        }
    }
}
// 用户没有通过身份验证
return Task.FromResult(AuthenticateResult.Fail("Invalid auth key."));