hrz
hrz

Reputation: 203

Error in logging in authentication against Active Directory with ASP.NET Core by LDAP

I'm implementing an ASP.NET Core project and I'm trying to authenticate the user login via LDAP to Active Directory. I'm using this link https://www.brechtbaekelandt.net/blog/post/authenticating-against-active-directory-with-aspnet-core-2-and-managing-users

in order to implement the authentication against Active Directory with ASP.NET Core. What I've tried in appsettings.json is like below:

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "CSDDashboardContext": "Server=xxxx;Database=CSS;Trusted_Connection=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

  "LdapSettings": {
    "ServerName": "par.fr", 
    "ServerPort": 389, 
    "UseSSL": false,
    "Credentials": {
      "DomainUserName": "par\\koli-h",
      "Password": "asdq/1998"
    },
    "SearchBase": "CN=Users,DC=par,DC=fr",
    "ContainerName": "CN=Users,DC=par,DC=fr", 
    "DomainName": "par.fr",
    "DomainDistinguishedName": "DC=par,DC=fr",
    "SearchProperty": "samAccountName" //????
  }
}

Now my problem is after running the project and entering the user: koli-h and pass: asdq/1998 the system shows me invalid username or password. My real username and password in the server are koli-h and asdq/1998. However, if I change my user in the code to for example koli-ha (adding a character in order to make the username incorrect) after running the project, the system shows me an error

Invalid Credentials

I appreciate if anyone could suggest me what is the problem that I can't log into the system.

Upvotes: 1

Views: 1659

Answers (2)

hrz
hrz

Reputation: 203

Thank you very much for your help. The problem was I should specify "mydomain.com" in new PrincipalContext(ContextType.Domain, "par")) for example par.com.

Upvotes: 1

marc_s
marc_s

Reputation: 755083

Contrary to what is stated in that blog post you referenced (which is 2 years old), the System.DirectoryServices and System.DirectoryServices.AccountManagement namespace are in fact supported on .NETStandard 2.0 and thus usable in .NET Core 2.x/3.x.

Check out the relevant Nuget page:

https://www.nuget.org/packages/System.DirectoryServices.AccountManagement/4.7.0

And thus, you can very easily use the "usual" code to validate user credentials:

using System.DirectoryServices.AccountManagement;

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "par"))
{
    // validate the user's credentials
    if (ctx.ValidateCredentials(userName, password)
    {
        // credentials are OK --> allow user in
    }
    else
    {
        // credentials aren't OK --> send back error message
    }
} 

Upvotes: 2

Related Questions