capture windows username in asp.net mvc request

[From]: http://stackoverflow.com/questions/2132807/capture-windows-username-in-asp-net-mvc-request

You can use HttpContext.Current.User.Identity.Name if you set up the site to use Windows Authentication. Many browsers will pass the username on transparently.

shareedit

Go to the Web.Config file for your application (be sure it’s the main one, not the Web.Config under Views), remark out <authentication mode="Forms"> if you see it, then add lines like this:

<authentication mode="Windows"/>
<identity impersonate="true"/>
<authorization>
  <allow roles="DOMAIN\PersonnelGroup" />
  <allow users="DOMAIN\jdoe"/>
  <deny users="*"/>
</authorization>

You don’t have to include the <authorization> section but it’s useful if you want to allow access for certain groups and users, and deny everyone else. When you use IE, the credentials get passed along automatically. You can test this by printing the username in your view:

@HttpContext.Current.User.Identity.Name

If you open your site using Firefox or any other browser besides IE, it will prompt you for the username and password because it’s not automatically passing along the credentials (although apparently you can get Firefox to pass along the credentials, as Dan Diplo mentions above).

If you want to pass these credentials along to another server, such as a SQLServer, it becomes more of a headache from my experience, because you run into a double hop issue. The only workaround I know of is to host IIS and SqlServer on the same server, or have a login for your intranet so you have the username and password to pass along to SQLServer.

shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s