Search code examples
c#asp.netauthenticationasp.net-coreactive-directory

Asp net Core Get user Windows username


Building an intranet in ASP .net CORE mvc, I need to get the Windows username of the current user for the login, I do not need to automaticaly login the user with Windows Authentication, I have already a custom login Controller to do that, I only need his username.
It work fine on local but I cannot get the username when on the IIS server :
Local :

Environment.UserName => VeronY 
System.Security.Principal.WindowsIdentity.GetCurrent().Name => Domain\VeronY

IIS server :

Environment.UserName => Intranet
System.Security.Principal.WindowsIdentity.GetCurrent().Name => APPPOOL\Intranet 

With Windows Auhtentication it auto login me which is not what I need. There must be 2 type of authentication : Automatic with AD and Manual with form manage by Identity Framework.


Solution

  • ASP .net doesn't seem to authorize 2 different types of connection, so I let the main site with form authentication and I 've created a small API :

    [Authorize]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpGet]
        public ActionResult Get()
        {
            return Json(User.Identity.Name);
        }
    }
    

    Configure with Windows Authentication.
    And here's the LoginController in the main website :

    String responseString = "";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://myapiURL");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync("api/values").Result;
                if (response.IsSuccessStatusCode)
                {
                    responseString = response.Content.ReadAsStringAsync().Result;
                    responseString = Regex.Unescape(responseString).Replace("\"","");//Because the response is something like \\"Domaine\\\\Username\"\
                }
                else
                {
                    return View();//server cannot be found or Windows authentication fail => form Login
                }
            }
            String username = "";
            String domain = "";
    
            if (responseString != "" && responseString.Contains("\\"))
            {
                domain = responseString.Split('\\')[0];
                username = responseString.Split("\\")[1];
                if(domain !="MYDOMAIN")
                {
                    return View();//Not in the correct domain => form Login
                }
            }
            else
            {
                return View();//Not the correct response => form Login
            }
            UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), username);
    
    
            if (null != user)
            {
                CustomAutomaticLogin(user)//All seems ok, try to log the user with custom login with AD informations
            }
            else
            {
               return View()//Not in AD => form login
            }
    }