Working with DirectoryServices in ASP.NET Core

前端 未结 5 1745
说谎
说谎 2021-02-02 14:22

I am upgrading my ASP.NET Core RC1 application to RC2. I have some references to System.DirectoryServices and System.DirectoryServices.AccountManagement

5条回答
  •  深忆病人
    2021-02-02 14:23

    If you only want to authenticate users in .NET Core 2.0, you only need to add System.DirectoryServices Nuget package (no need to add Microsoft.Windows.Compatibility nuget package). It is also supported in .NET Standard 2.0

    Note: I've only used below code in .NET Core 2.2, but the nuget compatibility info indicates that it works in .NET Core 2.0.

    To validate password use:

    var domainAndUsername = domain + @"\" + username;
    var entry = new DirectoryEntry(_path, domainAndUsername, pwd);
    
    object isValidPassword = null;
    try
    {
         // authenticate (check password)
         isValidPassword = entry.NativeObject;
    }
    catch (Exception ex)
    {
          _logger.Log.Debug($"LDAP Authentication Failed for {domainAndUsername}"); 
          return false;
    }
    

    Furthermore, if you want to search for user in directory, below should work:

    var search = new DirectorySearcher(entry) { Filter = "(SAMAccountName=" + username + ")" };
    search.PropertiesToLoad.Add("cn");
    
    var result = search.FindOne();
    

    According to Github Issue, System.DirectoryServices.AccountManagement isn't yet supported for LDAP. Beyond that, previous info provided by @zdub and @Bastyon still seems valid.

提交回复
热议问题