Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the way in ASP.NET Core 3.0 to get current authenticated User username?

I'm working on the latest ASP.NET Core 3.0 Angular template. What I need to know is how we can get authenticated user, username in ActionFilterAttribute.

The ClaimTypes.NameIdentifier returns the current user id, and ClaimTypes.Name returns the username which is null.

Here is my code:

enter image description here

where getUser has a UserId of d15f997a-6f65-4eb2-aecb-8b525361ae50

I've also register IHttpContextAccessor in the Startup class as follows:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<ApplicationUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        //Database Setup
        services.AddDbContext<HashooDBContext>(Configuration.GetConnectionString("DefaultConnection"));

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddControllersWithViews();
        services.AddRazorPages();
        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        return ContainerSetup.InitializeWeb(Assembly.GetExecutingAssembly(), services);
}

Controller.cs:

[Authorize]
[ApiController]
[Route("api/[controller]/{companycode}")]
public class DashboardTransactionsController : ControllerBase
{
    [CustomAuthorizationFilter("companycode")]
    public string Get()
    {
        return "Welcome";
    }
}

Please let me know what am I doing wrong?

like image 634
Ahmer Ali Ahsan Avatar asked Oct 20 '19 13:10

Ahmer Ali Ahsan


People also ask

How do I get current user in .NET Core?

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 property to access the username.

How do I get the current UserName in .NET using C#?

GetCurrent(). Name; Returns: NetworkName\Username. Gets the user's Windows logon name.

How do I find HttpContext current user identity name?

Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an . aspx page without using the fully qualified class reference to HttpContext. For example, you can use User.Identity.Name to get the name of the user on whose behalf the current process is running.


1 Answers

You can use IHttpContextAccessor

private readonly IHttpContextAccessor _httpContextAccessor;

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

And to get user name you can use

_httpContextAccessor?.HttpContext?.User?.Identity?.Name;

Or

 _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

Then register in your Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
like image 140
Tony Ngo Avatar answered Oct 22 '22 02:10

Tony Ngo