ASP.NET Core Identity ClaimsPrincipal 显示为空

ASP.NET Core Identity ClaimsPrincipal appears empty

在我的 LoginController 中,我已将 UserManager 和 SignInManager 注入到构造函数中,并成功验证了用户:

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

result.Succeeded 是真的。都好。我在浏览器中获得了一个授权 cookie。

在我的 _layout.cshtml 视图中,我想使用 SignInManager 检查我的用户是否已登录。 我将适当的部分注入到 cshtml 文件中,如下所示:

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

然后我使用代码检查用户 属性 是否登录。

@if (signInManager.IsSignedIn(User))

问题:用户声明主体似乎为空或未使用任何数据初始化。 signInManager.IsSignedIn 将始终 return false 即使我已成功进行用户身份验证。

我认为 SignInManager 应该创建我需要的所有默认声明和委托人。主体在 cshtml 视图中不可用还有其他原因吗?

编辑:添加了 startup.cs 代码

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?}");
        });
    }

您的项目将 cookie 身份验证与身份混合在一起。

只需从 Startup.cs 中删除以下代码:

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