Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting The Current User Name In ASP.NET Application

Tags:

c#

asp.net

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.

like image 595
Kevin Avatar asked Jul 19 '12 19:07

Kevin


2 Answers

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>
like image 143
SliverNinja - MSFT Avatar answered Sep 28 '22 12:09

SliverNinja - MSFT


If you need the current logged in user's identity from within any layer (or Project in your solution) then use:

string userId = Thread.CurrentPrincipal.Identity.GetUserId();

like image 35
Ehimah Obuse Avatar answered Sep 28 '22 13:09

Ehimah Obuse