Get the Current User in ASPNET Core How to Get the Current User in ASPNET httpcontext current user identity name is emptyUsing HttpContext in Async Task

This article explains an easy approach on how to get the Current User in ASP.NET Core.

You may find a need to get a logged-in username using your application in the IIS or Cloud-hosted app.

One can easily get the current user name from HttpContext in ASP.NET Core provided user details are transferred for the given session using cookies or other means. etc.

Today in this article, we will cover below aspects,

Below are the basic steps that need to be followed.

Using HTTPContext metadata

HTTPContext lets you access its metadata configured when the request reaches ASP.NET Core API.

This HttpContext sets the various headers including Username and password etc.

This context however also depends on the type of Authentication and Authorization schemes being used to validate the Users.

Getting Current UserName in Controller

Getting UserName in Controller is easy as you can directly access the HttpContext object within Controller.

You need to access HttpContext.User.Identity.Name the property to access the username.

Update Get method for the below code,

        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            UserName = HttpContext.User.Identity.Name;
            return Ok(UserName);
        }

Access current UserName in Repository or other Custom Components

Access the current Username in the Repository or other Custom modules using HttpContextAccessor.

HttpContextAccessor lets you access HTTPContext and its metadata in any other module.

Update ConfigureServices() in Startup.cs as below,

.NET Core 3.1 and Above( .NET 5 or .NET6 )

For the .NET Core version 3.1 and above and lower, please register the service for IHttpContextAccessor as below.

 public virtual void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddHttpContextAccessor();

        }

.NET Core 3.0 and lower version

For the lower version of .NET Core like .NET Core 2.2 and lower, please register the service for IHttpContextAccessor as below.

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            
        }

Dependency Inject (DI) interface IHttpContextAccessor in the Constructor as below,

     

class EmployeeRepository : IEmployeeRepository
      {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public EmployeeRepository( IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
...
      }



Getting UserName in Method

  

class EmployeeRepository : IEmployeeRepository
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public EmployeeRepository( IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }



Or Access HttpContext.User.Identity.Name in a method,

get username net core get username logged in mvc get username aspnet coreGet the Current User in ASPNET Core

Getting UserName in API Middleware

Similarly if needed you can read UserName in the middleware component by accessing HttpContext.

Note:

If you are trying to get a user name using the user identity then please follow the below configuration and the set authentication mode as Windows.

Below configuration let HttpContext.Current.User.Identity.Name set using the usernames logged in.

If Hosting in IIS Server – Set Authentication mode as Windows

This is the preferred setting for IIS-hosted services also where anonymousAuthentication needs to be set as false.

And Set the WindowsAuthentication as true.

"windowsAuthentication": true,
"anonymousAuthentication": false

If Debugging locally

If debugging locally to verify, Please update the launchSettings.json file for the Windows authentication setting as true in the ‘iisSettings’ section as below.

windowsAuthentication”: true,

“anonymousAuthentication”: false

HttpContext.User.Identity.Name is empty

If the above-discussed setting is not followed then you will get HttpContext.User.Identity.Name as empty or null.

Cloud-hosted app Windows authentication will also work if enabled with Windows Authentication using the Active Directory (AD group) or by following other security policy with in the enterprise infrastructure which let you sync up your User IDs with Server/Cloud.

Most enterprise Application uses secured cookies and session token details (with the help of redirection from their intranet sites to the cloud hosted web applicaiton) to send the actual user name logged in to an application.

HttpContext is not threadsafe so please follow the below additional guidelines for its proper usage,

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.