Skip to content

Authenticate with Active Directory (.Net Core)

Sevigor edited this page Jun 10, 2021 · 1 revision

Since the Active Directory Auth in the developer guide only works with the old .Net version, I figured I'd add a wiki page on how to setup Active Directory Authentication with .Net Core. It's pretty straightforward.

Note: I believe this will only work if the server/localmachine you're running on is directly connected to your network domain.


Create the class ActiveDirectoryService.cs inside the Modules/Administration/User/Authentication/ location.

using Serenity;
using Serenity.ComponentModel;
using System;
using System.DirectoryServices.AccountManagement;

namespace PROJECTNAMESPACE.Administration
{
    public class ActiveDirectoryService : IDirectoryService
    {
        public DirectoryEntry Validate(string username, string password)
        {
            var config = Config.Get<Settings>();
            using (var context = new PrincipalContext(ContextType.Domain, config.Domain))
            {
                bool isValid;
                try
                {
                    isValid = context.ValidateCredentials(username, password);
                }
                catch (Exception ex)
                {
                    Log.Error("Error authenticating user", ex, this.GetType());
                    return null;
                }

                if (!isValid)
                    return null;

                var identity = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);

                return new DirectoryEntry
                {
                    Username = identity.SamAccountName,
                    Email = identity.EmailAddress.TrimToNull(),
                    FirstName = identity.GivenName,
                    LastName = identity.Surname,
                };
            }
        }

        [Hidden, SettingScope("Application"), SettingKey("ActiveDirectory")]
        private class Settings
        {
            public string Domain { get; set; }
        }
    }
}

The package using System.DirectoryServices.AccountManagement; might throw an error. If so, you'll need to install the nuget package.

In Startup.cs add the following line inside the method ConfigureServices(). Don't forget to add the necessary usings.

services.AddSingleton<IDirectoryService, ActiveDirectoryService>();

Last thing you need to do is open up appsettings.json and add the following block inside of the AppSettings category

"ActiveDirectory": {
   "Domain": "YourDomainName"
}

Once you've added all of the above it should work seamlessly.

Clone this wiki locally