ASP.NET Core 2.0 Ldap Active Directory Authentication

ASP.NET Core 2.0 LDAP Active Directory Authentication

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

Active Directory Authentication by UPN in ASP.NET Core 3.0

Tao option is working. I also found another option, here https://www.brechtbaekelandt.net/blog/post/authenticating-against-active-directory-with-aspnet-core-2-and-managing-users with code https://github.com/brechtb86/dotnet/tree/master/brechtbaekelandt.ldap. This however was for Asp.Net Core 2.0.

I have updated this to run on Asp.Net Core 3.0, and published my code on GitHub https://github.com/CraigTolley/AspNetCore-LdapAuth. It currently also uses the Novell library. I'm not promising that it is perfect, but will hopefully help someone else too.

The code example shows functioning LDAP authentication, which then extracts the group memberships for the authenticated user to construct a set of roles and claims which can be used for authentication.

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

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
}
}

.net core 5 Windows Authentication and Active Directory resources

There's a nuget that handles this; System.DirectoryServices.AccountManagement

It's Windows only, there's a Novel ldap version that I think is cross platform.

To authenticate:

using (var ctx = new PrincipalContext(ContextType.Domain))
{
if (!ctx.ValidateCredentials(user_name, password))
throw new Exception("unknown username or password");

using (var userPrinciple = new UserPrincipal(ctx)) {
userPrinciple.SamAccountName = user_name;

using (var search = new PrincipalSearcher(userPrinciple))
{
UserPrincipal user = (UserPrincipal) search.FindOne();
if (user == null) {
throw new Exception("user authenticated but not found in directory");
}
return user; // auth'ed user
}
}
}

To authorize (by group membership):

using (var ctx = new PrincipalContext(ContextType.Domain))
{
using (var groupPrinciple = new GroupPrincipal(ctx))
{
groupPrinciple.SamAccountName = groupName;
using (var search = new PrincipalSearcher(groupPrinciple))
{
member_list = GetMembersOfPrincipalGroup((GroupPrincipal)search.FindOne());
}
// member_list contains all the users of a group.
// I cache these in a Dictionary for faster group membership checks
}
}

Note that the ContextType enum handles local machine users as well as domain.
Search on the nuget package for more examples.

How to use Active Directory Authentication in ASP.NET Core?

The best way is to use Windows authentication. However, that will only work if the server you run this on is joined to the domain (or a trusted domain).

If not, then you will have to use Forms Authentication, where the user enters their username and password, and you authenticate against AD in your code via LDAP. There are two ways to do this in .NET Core:

  1. If you will only run this on a Windows server, then you can install and use the Microsoft.Windows.Compatibility NuGet package.
  2. Use the third-party Novell.Directory.Ldap.NETStandard.

There are two answers on this question that describe how to implement both solutions.



Related Topics



Leave a reply



Submit