Search code examples
c#asp.net-coreasp.net-core-mvcwindows-authenticationroles

How to add Roles to Windows Authentication in ASP.NET Core


I created an asp.net core project in visual studio 2015 with windows authentication. I can't figure out how to add roles to the Identity.

I have a table with usernames for the windows account. And when the user opens the website the user is added to the Identity (I assume that's what happens, because I can display the username by User.Identity.Name) and I want to pull out Roles from another table and assign them to the user, is this possible? Or perhaps is there a better way to do it? (Why?, How?)

I couldn't find any examples specific examples related to windows authentication, but I have read the documentation and went through this guide. And I'm still stuck.


Solution

  • this is working code that I use to check is a user is in a role \ group, please use it at your leisure

    using System.Collections.Generic;
    using System.DirectoryServices.AccountManagement;
    using System.Linq;
    using System.Security.Principal;
    
    namespace Santander.IsUserInGroupOrRole_cs
    {
    
    public class IsUserInRole
    {
        public static bool IsInGroup(string groupName)
        {
            var myIdentity = GetUserIdWithDomain();
            var myPrincipal = new WindowsPrincipal(myIdentity);
            return myPrincipal.IsInRole(groupName);
        }
    
        public bool IsInGroup(List<string> groupNames)
        {
            var myIdentity = GetUserIdWithDomain();
            var myPrincipal = new WindowsPrincipal(myIdentity);
    
            return groupNames.Any(group => myPrincipal.IsInRole(group));
        }
    
        public static WindowsIdentity GetUserIdWithDomain()
        {
            var myIdentity = WindowsIdentity.GetCurrent();
            return myIdentity;
        }
    
        public static string GetUserId()
        {
            var id = GetUserIdWithDomain().Name.Split('\\');
            return id[1];
        }
    
        public static string GetUserDisplayName()
        {
            var id = GetUserIdWithDomain().Name.Split('\\');
    
            var dc = new PrincipalContext(ContextType.Domain, id[0]);
            var adUser = UserPrincipal.FindByIdentity(dc, id[1]);
            return adUser.DisplayName;
    
        }
    }
    }