1

I am using cookie authentication and authorization in .Net Core. My issue is after SignInAsync, I am getting User.identity.name null and also claims count 0.
Here is my controller code

     ClaimsIdentity identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, "Hunzla-1"),
                        new Claim(ClaimTypes.Role, "Admin")
                    }, CookieAuthenticationDefaults.AuthenticationScheme);  
 var principal = new ClaimsPrincipal(identity);
 var login = HttpContext.SignInAsync(principal);
 string s=User.Identity.Name;  //s is empty

My Startup.cs code

 public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {  options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(o => o.LoginPath = new PathString("/account/login"));
                      }
    }
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseCookiePolicy();
                app.UseAuthentication();
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
Hunzla Ali
  • 383
  • 2
  • 5
  • 22
  • 1
    These are only populated on **the next request** (if the cookie could be set properly and is still valid on the next request), so it's "by design" ;) (User property is set in the authentication middleware, but when you sign in know, the middleware has already been processed, so it will be set on next call) – Tseng Mar 12 '19 at 19:05
  • But i need to get it after 'HttpContext.SignInAsync'? is it possible? or can system wait till authentication middleware processed? – Hunzla Ali Oct 02 '19 at 09:43
  • You can't. Reconsider your design. Why do you even need it? At this point you already know who the user is – Tseng Oct 02 '19 at 11:50
  • I mean, the `principal` is already populated by you. Typically after the login you redirect the user to the resource he was trying to access. Redirecting causes a new request and on that request the User property will be properly populated – Tseng Oct 02 '19 at 12:01

0 Answers0