Search code examples
.net-coreweb-applicationsazure-active-directorywindows-authenticationrazor-pages

Getting the full user name from User.Identity in Razor.Pages project when authenticating using Azure AD


I am developing my Razor.Pages web application in .Net Core 3.1 and I configured the authentication using my company AD. I can use without any problem the User.Identity.Name to get the user@domain value but I need to get the full name of the person that is logged in so that I can filter some results of a query to an SQL DB based on the user's full name.

I tried googling around but didn't find anything a solution to my problem. Thanks!


Solution

  • After doing some digging around I finally managed to create a method that receives the User.Identity.Name of the logged in user and returns the full name. Bellow is a snippet of the method!

        public static string GetFullName(string domainName)
        {
            string fullName = "";
            UserPrincipal principal;
    
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
            {
                principal = UserPrincipal.FindByIdentity(ctx, domainName);
            }
    
            if (principal != null)
                fullName = $"{principal.GivenName} {principal.Surname}";
            else
                fullName = domainName;
    
            return fullName;
        }