If you want to get a users username in a site that uses authentication then you can just use the User object and that will provide all claims associated with that user.

However if you want to get the username for a user where they’re not required to authenticate first then it’s a bit trickier. In order to get the Windows username of a user you need to update the launchSettings.json file to requets the Windows username by telling the browser Windows authentication is required and then it can be retrieved from the request context.

This obviously shouldn’t be used in an actual security context but can be handy to know in some situations.

launchSettings.json

First update the windowsAuthentication and anonymousAuthentication properties in your launchSettings.json file. Anonymous site access is still possible.

"iisSettings": {
	"windowsAuthentication": true,
	"anonymousAuthentication": false,
	"iisExpress": {
		"applicationUrl": "http://localhost:53321",
		"sslPort": 44320
	}
}

HomeController.cs

You can then get a users Windows username from a controller using the below code.

public IActionResult Index()
{
	string userName = HttpContext.User.Identity.Name;
	return View(userName);
}

Dependency Injection

If you want to access the Windows username in the Startup script or in repositories then you can dependency inject the HttpContextAccessor which will allow access to the User object. Further details can be found here.

 public virtual void ConfigureServices(IServiceCollection services)
{
	services.AddHttpContextAccessor();
	services.AddControllers();
}

Leave a Reply

Your email address will not be published. Required fields are marked *