ASP.NET Core 2.0 LDAP Active Directory Authentication

后端 未结 3 1425
别那么骄傲
别那么骄傲 2020-11-27 11:47

I have found a lot of information from the past saying that LDAP authentication isn\'t enabled yet but you can get around that using third party packages. However, it seems

3条回答
  •  盖世英雄少女心
    2020-11-27 12:13

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

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

    Install-Package Microsoft.Windows.Compatibility 
    

    At the time, I needed a preview version, so I appended -Version 2.0.0-preview1-26216-02 on the end of this command

    Then, add using statements for System.DirectoryServices and System.DirectoryServices.AccountManagement

    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 { 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."));
    

提交回复
热议问题