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.



10 thoughts on “How to Get the Current User in ASP.NET Core

  1. “HttpContext is not threadsafe so please follow the below additional guidelines for its proper usage”

    That links to some mongodb-id article.

  2. Hi, Can anyone help with the settings required in case the app needs to be run on PCF (Linux container). The mentioned launchsettings.json settings won’t work.
    I am using Microsoft.AspNetCore.Authentication.Negotiate package to use NegotiateDefaults.AuthenticationScheme.
    Any pointers?

    1. Hey Tony – There are multiple ways to implement it. However, Have you tried – return RedirectToPage(..)? You can specify your Home page on the Redirect page after successful authentication.Hope it helps.

      1. Hi,
        Thanks for the reply.It is my first application Net core 5 (intranet windows os).
        Authentication occurs automatically without identity, so where should I enter the redirection?

  3. Hi ,
    If “windowsAuthentication”: true, “anonymousAuthentication”: false, I am Getting CORS Error. If I do “windowsAuthentication”: true, “anonymousAuthentication”: true, current User is Empty .

    Please Help

    1. Hi Bhupesh- You might be getting CORS error because of cross-domain calls. Please make sure to enable CORS policy along with your authentication schemes mechanism. Please see here on how to enable CORS in ASP.NET Core as references . Please note CORS middleware order should be correct in the API pipeline.

  4. Hi,
    By implementing “windowsAuthentication”: true and”anonymousAuthentication”: false would enable browser to prompt for user credential each time when application launched.

    How can I capture userID without Browser prompting for user credential since user already logged in to their computer?

    Thanks,
    Brandon.

    1. Hey Brandon – Thanks for your query. With the above settings, it did not prompt me for user credentials (IE or Chrome) and gives me my current ID. Could you confirm you still see a prompt?

Leave a Reply

Your email address will not be published. Required fields are marked *