Trido
Trido

Reputation: 545

Pulling current username in ASP.NET

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;

Upvotes: 0

Views: 2950

Answers (3)

Brandon
Brandon

Reputation: 993

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

Upvotes: 2

Mazhar Khan
Mazhar Khan

Reputation: 404

You can use

HttpContext.Current.User.Identity.Name

It will give you Domain\UserName

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

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

Upvotes: 0

Related Questions