[c#] How to get user name using Windows authentication in asp.net?

I want to get user name using Windows authentication

Actually I implemented "Sign in as different user",when click this button Windows security will appear there we can give credentials.

In that time if I give some other credential it is taking current user name only. How to get that given credential user name from windows security?

Host application in IIS then anonymous authentication has disabled and windows authentication was enabled.

web.config:

<system.web>
    <compilation debug="true" targetFramework="4.0" />
  <identity impersonate="true"/>
  <authorization>
      <allow users="*"/>
      <deny users="*"/>
  </authorization>
</system.web>
<system.webServer>
    <directoryBrowse enabled="true" />
    <security>
        <authentication>
            <anonymousAuthentication enabled="false" />
            <windowsAuthentication enabled="true" />
        </authentication>
    </security>

.cs

Here I am getting the default User name always

string fullName = Request.ServerVariables["LOGON_USER"];

Any ideas? Thanks in advance

The answer is


I think because of the below code you are not getting new credential

string fullName = Request.ServerVariables["LOGON_USER"];

You can try custom login page.


These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source


You can read the Name from WindowsIdentity:

var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
return Ok(user);

Username you get like this:

var userName = HttpContext.Current.Request.LogonUserIdentity?.Name;

You can get the user's WindowsIdentity object under Windows Authentication by:

WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;

and then you can get the information about the user like identity.Name.

Please note you need to have HttpContext for these code.


It depends on the configuration of the application as well as on IIS as this gentleman in the below link has rightfully explained. Please see his article below

http://richhewlett.com/2011/02/15/getting-a-users-username-in-asp-net/


This should work:

User.Identity.Name

Identity returns an IPrincipal

Here is the link to the Microsoft documentation.


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 authorization

How to send custom headers with requests in Swagger UI? How do you create a custom AuthorizeAttribute in ASP.NET Core? ASP.NET Web API : Correct way to return a 401/unauthorised response How to get http headers in flask? How to define the basic HTTP authentication using cURL correctly? basic authorization command for curl MongoDB "root" user How to use basic authorization in PHP curl How to get user name using Windows authentication in asp.net? Python requests library how to pass Authorization header with single token

Examples related to windows-authentication

How to get user name using Windows authentication in asp.net? Authentication issue when debugging in VS2013 - iis express "Cannot create an instance of OLE DB provider" error as Windows Authentication user Connection string using Windows Authentication Receiving login prompt using integrated windows authentication IIS Express Windows Authentication IIS7 folder permissions for web application How to get the current user's Active Directory details in C# IIS7: Setup Integrated Windows Authentication like in IIS6

Examples related to windows-security

How to get user name using Windows authentication in asp.net? How to get HttpClient to pass credentials along with the request?