Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Authentication - Getting current user name

In my MVC application I want to render a table in a cshtml file, if the current log in user is some x person. I am using windows authentication and I have made the following changes in web.config file.

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

And in my controller when I am trying to access the current user name I am not getting any user name. I am trying the following:

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

This above line was working before. But I don't know whats wrong now. Also I have hosted my application on IIS now.

like image 955
Jash Avatar asked Jan 23 '12 07:01

Jash


2 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;
    }
}
like image 59
jgauffin Avatar answered Oct 12 '22 19:10

jgauffin


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

  1. Anonymous Authentication - Set to "Disabled"
  2. Windows Authentication - Set to "Enabled"

By default these are set to the opposite of what you're probably looking for.

Web project properties

(Image sourced from MSDN)

like image 37
Bern Avatar answered Oct 12 '22 17:10

Bern