且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core 2.0 LDAP Active Directory身份验证

更新时间:2022-06-04 07:38:39

感谢Win的答案,指出我需要使用 Windows兼容包,我能够弄清楚这一点.

Thanks to Win's Answer for pointing out that I needed to use Windows Compatibility Pack, I was able to figure this out.

我要做的第一件事是安装 Nuget软件包 >

The first thing I had to do was install the Nuget package

Install-Package Microsoft.Windows.Compatibility 

当时,我需要一个预览版,所以我在命令末尾附加了-Version 2.0.0-preview1-26216-02

然后,为System.DirectoryServicesSystem.DirectoryServices.AccountManagement

然后,只需将此逻辑插入我的HandleAuthenticateAsync方法中即可:

Then, just plug this logic into my HandleAuthenticateAsync method:

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)) {
            // other logic to verify user has correct permissions

            // User authenticated and authorized
            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));
        }
    }
}

// User not authenticated
return Task.FromResult(AuthenticateResult.Fail("Invalid auth key."));