Windows Authentication - Get Current Username

In my MVC application, I want to display the table in the cshtml file if the current user in the log is x people. I use Windows authentication and I made the following changes to the web.config file.

<authentication mode="Windows"> </authentication> 

And in my controller, when I try to access the current username, I don't get any username. I am trying to do the following:

 ViewBag.LogInUserName = Request.RequestContext.HttpContext.User.Identity.Name; 

This line above worked. But I do not know what happened now. I have also posted my application on IIS now.

+6
source share
3 answers

You need to put the [Authorize] attribute on your controller.

You can use User.Identity.Name in your controllers.

 [Authorize] public class YourController : Controller { public ActionResult SomeAction() { var userName = User.Identity.Name; } } 
+11
source

Take a look at the properties of a web project, in particular:

  • Anonymous Authentication - Set to Disabled
  • Windows Authentication - Set to Enabled

By default, they are set opposite to what you are probably looking for.

Web project properties

(Image obtained from MSDN )

+11
source

A little late, but it may happen to others in the future.

I had the same problem after deploying my site on a new IIS server and anonymous authentication was enabled, so make sure that anonymous authentication is disabled and it should work.

+1
source

Source: https://habr.com/ru/post/906632/


All Articles