For some reason I can't get the windows username on an impersonated call. I have followed the answers here but not getting the same result.
On server A I have a intranett ASP.MVC application with only windows authentication in IIS.
In the web config for the mvc application on server A, I use impersonation.
Code for calling web api
var impersonationContext = WindowsIdentity.GetCurrent().Impersonate();
using (impersonationContext)
{
var client = GetHttpClient();
return await client.PostAsync("services/ExecuteCommand/Execute", httpContent);
}
private HttpClient GetHttpClient()
{
var httpClientHandler = new HttpClientHandler
{
UseDefaultCredentials = _commandServiceUseDefaultCredentials
};
var client = new HttpClient(httpClientHandler)
{
BaseAddress = new Uri(ConfigurationManager.AppSettings["CommandServiceBaseUrl"].ToString()),
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
On server B i have a ASP.Net Web API (Core) project with windows authentication
In the web config for the web api on server B a specify using windows authentication, but NOT impersonation.
I'm trying to get the windows username for the person browsing my mvc application. I have tried a lot so I ended up with this method to get them all.
private string GetUserName()
{
var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsIdentity windowsIdentity2 = null;
if (System.ServiceModel.OperationContext.Current != null)
if (System.ServiceModel.OperationContext.Current.ServiceSecurityContext != null)
windowsIdentity2 = System.ServiceModel.OperationContext.Current.ServiceSecurityContext.WindowsIdentity;
var httpContextIdentity = System.Web.HttpContext.Current.User.Identity;
return string.Format("{0}_{1}_{2}_{3}_{4}",
System.Environment.UserName ?? "",
User.Identity.Name,
windowsIdentity != null ? windowsIdentity.Name : string.Empty,
windowsIdentity2 != null ? windowsIdentity2.Name : string.Empty,
httpContextIdentity != null ? httpContextIdentity.Name : string.Empty);
}
This yields this result
System.Environment.UserName: ServerB App_pool user without domain
User.Identity.Name: Domain\ServerA$
System.Security.Principal.WindowsIdentity.GetCurrent().Name: ServerB domain\app_pool user
System.ServiceModel.OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name: (null)
System.Web.HttpContext.Current.User.Identity: Domain\ServerA$
So how can I get the windows username for the end user of my mvc app?