in my .net core mvc application I try to get the user claims in my user service. but the claims list is empty.
public class CurrentUserService : ICurrentUserService
{
    public CurrentUserService(IHttpContextAccessor httpContextAccessor)
    {
        UserId = httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
    }
    public string UserId { get; }
}

but in the page there are claims. What is the difference?

ConfigureServices:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI();
        services.AddHttpContextAccessor();
        services.AddScoped<ICurrentUserService, CurrentUserService>();
        services.AddTransient<IEmailSender, EmailSender>();
        services.Configure<EmailOptions>(options =>
        {
            Configuration.GetSection("Email").Bind(options);
        });
        services.AddPingIdentity(Configuration);
        services.AddApplication();
        services.AddInfrastructure(Configuration);
        services.AddConfiguredRazorPages();
    }

The problem is that the CurrentUserService is instantiated by the dependency injection framework before the Authentication middleware has set the claims of HttpContext.User. As the HttpContext.User is accessed (using the IhttpContextAccessor) in the constructor of the CurrentUserService, the claims are not yet available.
A potential solution is to access the HttpContext.User property when accessing the UserId property of ICurrentUserService.
public class CurrentUserService : ICurrentUserService
{
    private readonly IHttpContextAccessor httpContextAccessor;
    public CurrentUserService(IHttpContextAccessor httpContextAccessor)
    {
        this.httpContextAccessor = httpContextAccessor;
    }
    public string UserId => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With