[c#] How to get current user who's accessing an ASP.NET application?

To get the current logged in user at the system I use this code:

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

I work on an ASP.NET application where I need this information. So I've put my application on a server and tried the code above, and I get "Network Service" in the string opl. I need to know the current user of the PC who accesses my ASP.NET application.

This question is related to c# asp.net windows-server-2008

The answer is


The best practice is to check the Identity.IsAuthenticated Property first and then get the usr.UserName like this:

string userName = string.Empty;

if (System.Web.HttpContext.Current != null && 
    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
    System.Web.Security.MembershipUser usr = Membership.GetUser();
    if (usr != null)
    {  
        userName = usr.UserName;
    }
}

I ran in the same issue.

This is what worked for me:

Setting up Authentication in IIS Panel

Setting up Properties of Windows Authentication in IIS

Setting up Properties of Windows Authentication in IIS NTLM has to be the topmost

NTLM has to be the topmost. Further Web.config modifications, make sure you already have or add if these do not exist:

<system.web>

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

</system.web>

 <!-- you need the following lines of code to bypass errors, concerning type of Application Pool (integrated pipeline or classic) -->

<system.webServer>
   <validation validateIntegratedModeConfiguration="false"/>
</system.webServer>

See below a legit explanation for the two nodes and

Difference between <system.web> and <system.webServer>?

And, of course , you get the username by

//I am using the following to get the index of the separator "\\" and remove the Domain name from the string
int indexOfSlashChar = HttpContext.Current.User.Identity.Name.IndexOf("\\"); 

loggedInWindowsUserName = HttpContext.Current.User.Identity.Name.Substring(indexOfSlashChar + 1);

You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.

Use this:

HttpContext.Current.User.Identity.Name

Don't look too far.

If you develop with ASP.NET MVC, you simply have the user as a property of the Controller class. So in case you get lost in some models looking for the current user, try to step back and to get the relevant information in the controller.

In the controller, just use:

using Microsoft.AspNet.Identity;

  ...

  var userId = User.Identity.GetUserId();
  ...

with userId as a string.


The general consensus answer above seems to have have a compatibility issue with CORS support. In order to use the HttpContext.Current.User.Identity.Name attribute you must disable anonymous authentication in order to force Windows authentication to provide the authenticated user information. Unfortunately, I believe you must have anonymous authentication enabled in order to process the pre-flight OPTIONS request in a CORS scenario.

You can get around this by leaving anonymous authentication enabled and using the HttpContext.Current.Request.LogonUserIdentity attribute instead. This will return the authenticated user information (assuming you are in an intranet scenario) even with anonymous authentication enabled. The attribute returns a WindowsUser data structure and both are defined in the System.Web namespace

        using System.Web;
        WindowsIdentity user;
        user  = HttpContext.Current.Request.LogonUserIdentity;

Using System.Web.HttpContext.Current.User.Identity.Name should work. Please check the IIS Site settings on the server that is hosting your site by doing the following:

  1. Go to IIS ? Sites ? Your Site ? Authentication

    IIS Settings

  2. Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.

    Authentication

  3. Now System.Web.HttpContext.Current.User.Identity.Name should return something like this:

    domain\username


The quick answer is User = System.Web.HttpContext.Current.User

Ensure your web.config has the following authentication element.

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

Further Reading: Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to windows-server-2008

Multiple -and -or in PowerShell Where-Object statement The FastCGI process exited unexpectedly Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory How can I enable the Windows Server Task Scheduler History recording? IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service Gradle proxy configuration Installing Tomcat 7 as Service on Windows Server 2008 How to get current user who's accessing an ASP.NET application? ASP.Net which user account running Web Service on IIS 7? A process crashed in windows .. Crash dump location