0

I want IIS to grab the Active Directory username of the person viewing the page. Is this possible? I thought I might be able to do it via ASP.NET Authentication but when I tried it, I got a '401 Unauthorized: Access is denied due to invalid credentials' error message. Basically, what I want to do is get the web page to grab the current username, do a comparison to see if this person is a member of a specific security group and if so, display some content. All that works great on my local PC using the VS2010 inbuilt test server, but it is just pulling my AD details. Now that I have it all working, I want to move it to a test server running IIS7 to get it working there.

The only code I have in my default.aspx Code Behind (which worked on my local machine) is as follows:

string[] arr = System.Web.HttpContext.Current.Request.LogonUserIdentity.Name.Split('\\');

if (arr.Length > 0)
{
    lblDomain.Text = arr[0].ToString();
    lblUser.Text = arr[1].ToString();
}

From what I found here (http://stackoverflow.com/questions/10584545/activedirectory-current-username-in-asp-net) it looks like what I want is possible, but I wonder if it is something to do with my Code Behind. I am also not sure if I need something special in my Web.Config. I did have the following in there, but I got a 500 error.

<authentication mode="Windows"/>
<identity impersonate="true"/>

I have tried the answer to the above Stack Overflow question but am still getting 500 errors. Any hints would be greatly appreciated.

Also tried the following but still getting 500 errors. Not sure where it is going wrong.

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

And:

string userName = Environment.UserName;
Trido
  • 561
  • 2
  • 13
  • 35

3 Answers3

2

In IIS, try enabling windows authentication and then disabling all other forms of authentication (including anonymous).

Brandon
  • 983
  • 6
  • 15
  • That did it. While it will prompt for a username and password, because of trusted sites, it won't appear for our domain users. – Trido Oct 29 '12 at 06:04
0

Environment.UserName will be set to what you want if impersonation is turned on.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I did that but am still getting these damned 500 errors. I know they are generic errors, but it would be nice if they could give you more info. Especially because I don't have access to configure better error messages in IIS7. – Trido Oct 26 '12 at 01:47
0

You can use

HttpContext.Current.User.Identity.Name

It will give you Domain\UserName
Mazhar Khan
  • 396
  • 4
  • 15