Search code examples
asp.net-core.net-coreasp.net-identityclaims-based-identity

HttpContext.User.Claims and IHttpContextAccessor both returns empty value after successful login


HttpContext.User.Claims and IHttpContextAccessor both returns empty value after successful login in .NET Core 2.2 Here my Startup Services,

  services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")
                     ,b=>b.MigrationsAssembly("AdaptiveBizapp")));

            services.AddDbContext<Project_Cost_Management_SystemContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Project_Cost_Management_SystemContext") 
                    , b => b.MigrationsAssembly("AdaptiveBizapp")));

            services.AddDefaultIdentity<ApplicationUser>()
                .AddRoles<ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                 .AddDefaultTokenProviders();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;

            });
            services.ConfigureApplicationCookie(options => {
                options.LoginPath = "/Account/login";
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;                
                });
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });
 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 

and my Configure section,

 app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy(); 

            app.UseSession();

            app.UseAuthentication(); 
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
             name: "area",
             template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            });

enter image description here

I used Identity and Role based authorization. After login successful, in HomeController when i read user claims or NameIdentifier is empty. But when i read in same LoginController It has value at ClaimPrincipal,

  public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
        {
            var principal =await base.CreateAsync(user);

            // Add your claims here
            ((ClaimsIdentity)principal.Identity).
               AddClaims(new[] {
         new System.Security.Claims.Claim(ClaimTypes.NameIdentifier,
            user.UserName.ToString()) 
            });


            return principal;
        }

enter image description here

enter image description here

enter image description here


Solution

  • if you want use Depency Injection for IHttpContextAccessor you need to add :

    public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
            ...
            services.AddHttpContextAccessor();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            ...
            }
        }