I am using Windows Authentication with a .net core 3.1 application. I would like to retrieve the current user name but it's always null. I have not been able to deploy this application to IIS yet so this is happening while debugging with IISExpress.
launchSettings.json:
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:52362",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthorization();
services.AddHttpContextAccessor();
services.AddMvc();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
}
Controller:
[Authorize]
[ApiController]
[Route("[controller]")]
public class FilingController : Controller
{
private readonly string _currentUserName;
public FilingController(IHttpContextAccessor accessor)
{
//This is always null
_currentUserName = accessor.HttpContext.User.Identity.Name;
}
}
Here is the Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseIISIntegration();
webBuilder.UseIIS();
});
}
This occurs after a successful login. Why is the Name null, how can this be fixed?