Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Claims in IHttpContextAccessor are empty

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; }
}

Service

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

Page

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();
    }

enter image description here

like image 873
Marko Avatar asked Oct 30 '25 04:10

Marko


1 Answers

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);
}
like image 60
Gaste Avatar answered Nov 01 '25 18:11

Gaste