Reputation: 356
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 intranet ASP.NET MVC application with only Windows authentication in IIS.
In the web.config
for the ASP.NET 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 Core Web API 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 ASP.NET Core 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 ASP.NET Core MVC app?
Upvotes: 1
Views: 1766