Authenticate users inside .NET 6.0 Asp.NET core MVC using LDAP

john john 941 Reputation points
2022-10-07T10:51:18.867+00:00

I am creating a new ASP.NET core MVC web application based on .NET 6.0, and i want to authenticate the users using our windows 2016 LDAP server, so i benefit from this link @ https://thesoftwayfarecoder.com/ldap-authentication-in-asp-net-core/ although i am using .NET 6.0 unlike the link which uses older version.

So i did the following:-

1- I created a new ASP.NET Core MVC Project .NET 6.0.

2- Define to use User Accounts:-

248466-image.png

3- Install NuGet package – Microsoft.Windows.Compatibility:-

4- define our configuration to query our Active Directory:

public class LdapConfig  
  
    {  
        public string Path { get; set; }  
        public string UserDomainName { get; set; }  
    }  

5- In our appsettings.json, we add an Ldap section, which contains the path and userDomainName values:

{  
  "Ldap": {  
    "Path": "<<LDAP Path>>",  
    "UserDomainName": "<<Domain Name>>"  
  }  
}  

6- Add the following inside the program.cs:- We will use the Options pattern to retrieve our Ldap configuration. In order for us to bind to our LdapConfig, call the Configure method in the ConfigureServices method of our Startup.cs file:

public void ConfigureServices(IServiceCollection services)  
{  
    // read LDAP Configuration  
    builder.Services.Configure<LdapConfig>(builder.configuration.GetSection("Ldap"));  
}  

7- define an interface for our authentication service. This interface is needed for us to use dependency injection later on when we need our authentication service:

public interface IAuthenticationService  
{  
    User Login(string userName, string password);  
}  

8- reference a User data model, which may be defined as follows (depending on what data is available for your User model):

public class User  
{  
    public string UserName { get; set; }  
    public string DisplayName { get; set; }  
    // other properties  
}  

9- implement our LdapAuthenticationService:

public class LdapAuthenticationService : IAuthenticationService  
{  
    private const string DisplayNameAttribute = "DisplayName";  
    private const string SAMAccountNameAttribute = "SAMAccountName";  
      
    private readonly LdapConfig config;  
          
    public LdapAuthenticationService(IOptions<LdapConfig> config)  
    {  
        this.config = config.Value;  
    }  
    public User Login(string userName, string password)  
    {  
        try  
        {  
            using (DirectoryEntry entry = new DirectoryEntry(config.Path, config.UserDomainName + "\\" + userName, password))  
            {  
                using (DirectorySearcher searcher = new DirectorySearcher(entry))  
                {  
                    searcher.Filter = String.Format("({0}={1})", SAMAccountNameAttribute, userName);  
                    searcher.PropertiesToLoad.Add(DisplayNameAttribute);  
                    searcher.PropertiesToLoad.Add(SAMAccountNameAttribute);  
                    var result = searcher.FindOne();  
                    if (result != null)  
                    {  
                        var displayName = result.Properties[DisplayNameAttribute];  
                        var samAccountName = result.Properties[SAMAccountNameAttribute];  
                          
                        return new User  
                        {  
                            DisplayName = displayName == null || displayName.Count <= 0 ? null : displayName[0].ToString(),  
                            UserName = samAccountName == null || samAccountName.Count <= 0 ? null : samAccountName[0].ToString()  
                        };  
                    }  
                }  
            }  
        }  
        catch (Exception ex)  
        {  
            // if we get an error, it means we have a login failure.  
            // Log specific exception  
        }  
        return null;  
    }  
}  

10- register our LdapAuthentication service for dependency injection. Add the following in the ConfigureServices method of our program.cs:

builder.Services.AddScoped<IAuthenticationService, LdapAuthenticationService>();  

now i am not sure how i can force the login action method to use the above logic? where currently the build-in login method is not exposed to be modified? and should i use "Individual Accounts"? or another template?

Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,165 questions
{count} votes