Search code examples
c#windows-authenticationasp.net-core-3.1

Implement Windows Authentication for .NET Core 3.1 Web App


I have created an internal Razor Pages Web App using .NET Core 3.1. I want to only give access to users who are part of an Active Directory group. I don't want them to have to go through the hassle of creating yet more username/passwords. But I haven't been able to get it working.

I followed the Microsoft Documentation and created a starter app and added a web.config file as described in the docs. When I launch from Visual Studio 2019, the browser displays

enter image description here

  1. How can I get this working?
  2. How do I set it up to allow only users in a certain group to have access? I'm not concerned with roles at the moment. I want to allow full access, but lock out anyone not in the group. Thanks.

Solution

  • I was able to figure this out. I had my IT department add a special group for the users of the application and search for that group.

        public bool IsInGroup(string groupName)
        {
            var groups = new List<string>();
            
            var wi = (WindowsIdentity)User.Identity;
            if (wi.Groups != null)
                foreach (var group in wi.Groups)
                {
                    try
                    {
                        groups.Add(group.Translate(typeof(NTAccount)).ToString());
                    }
                    catch (Exception ex)
                    {
                        logger.LogInformation($"User = {User.Identity.Name}; Error = {ex.Message}");
                        throw;
                    }
                }
            return groups.Contains(groupName);
        }