Kevin Kevin - 3 months ago 8
ASP.NET (C#) Question

Getting The Current User Name In ASP.NET Application

I am running a webpage that needs to be able to read the login id of the current user. Here is the code I am using:

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


Currently this returns the correct login but when I use it in this method:

protected Boolean isPageOwner()
{
string id = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
alert("User: " + id);
if (id.Equals(pageOwnerID))
{
return true;
}
if (accessPermission.ContainsKey(id))
{
return true;
}
return false;
}


the method returns false even though the id returned is identical to pageOwnerID. I'm really not sure which part of this I am having a problem with.

On a side note, my login id is of the form string1/string2 but the code retrieves it as string1 + string2 without the slash.

Any advice is appreciated.

Regards.

Answer

Try using this to retrieve the username....

if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
   string username = System.Web.HttpContext.Current.User.Identity.Name;
}

It sounds like windows authentication is not being used - you need to disable anonymous access and enable windows integrated security.

Add this to your web.config...

<system.web>
 <authentication mode="Windows"/>
  <authorization>
    <deny users="?"/> 
  </authorization>
</system.web>