Home > Back-end >  ASP.NET Core Identity ClaimsPrincipal appears empty
ASP.NET Core Identity ClaimsPrincipal appears empty

Time:04-28

In my LoginController, I have injected UserManager and SignInManager into the constructor, and successfully authenticate a user with:

var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, false);

result.Succeeded is true. All good. I get an auth cookie in my browser.

On my _layout.cshtml view, I want to use the SignInManager to check if my user is signed in. I inject the proper parts into the cshtml file like this:

@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> signInManager
@inject UserManager<ApplicationUser> userManager

Then I use code to check if the User property is logged in.

@if (signInManager.IsSignedIn(User))

Problem: it looks like User claims principal is empty or not initialized with any data. signInManager.IsSignedIn will always return false even though I had a successful user authentication.

I thought that SignInManager was supposed to create all the default claims and principal that I needed. Is there another reason why the principal would not available on the cshtml view?

EDIT: added startup.cs code

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

        services.AddMvc();
        services.AddControllersWithViews();
        services.AddRazorPages();
        services.AddInfrastructure();

        // For Identity
        services.AddIdentity<ApplicationUser, IdentityRole>(
            options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<DocumentsContext>()
        .AddDefaultTokenProviders();

        services.ConfigureApplicationCookie(options => {
            options.Cookie.Name = "Wdd.Identity.User";
            options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
            options.SlidingExpiration = true;
            options.LoginPath = "/Login/Login";
            options.LogoutPath = "/Account/Logout";
        });
        
        // Adding Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        });

        services.Configure<IdentityOptions>(options =>
        {
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 6;
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 3;
        });

        services.Configure<MailSettings>(Configuration.GetSection("MailSettings"));
        services.Configure<AppConfiguration>(Configuration.GetSection("appConfiguration"));

        InitCommon();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();
        
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

CodePudding user response:

Your project mixs cookie authentication together with Identity.

Just remove the following code from the Startup.cs:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
  • Related