ASP.NET Core Identity中SignInManager.IsSignedIn(User)始终返回false问题
问题诊断与解决方案
你的核心问题是认证Scheme不匹配,导致SignInManager.IsSignedIn(User)无法识别登录状态。以下是具体问题点和修复步骤:
问题根源
- 默认认证Scheme冲突:你手动将
AddAuthentication的默认Scheme设置为CookieAuthenticationDefaults.AuthenticationScheme,但ASP.NET Core Identity的SignInManager默认使用IdentityConstants.ApplicationScheme生成登录Cookie。两者不一致时,认证中间件无法识别Identity生成的登录凭证。 - 重复的Cookie配置:你多次调用
AddCookie(包括Identity的内置Scheme和自定义Cookie),导致Cookie配置混乱,覆盖了Identity的默认登录Cookie设置。
修复步骤
1. 调整认证默认Scheme
将AddAuthentication的默认Scheme改为Identity的内置应用Scheme:
builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme; options.DefaultScheme = IdentityConstants.ApplicationScheme; options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidAudience = builder.Configuration["Jwt:Audience"], ValidIssuer = builder.Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) }; });
2. 使用Identity的Cookie配置方法
移除独立的AddCookie配置,改用ConfigureApplicationCookie来配置Identity的登录Cookie,确保和SignInManager的Scheme一致:
// 在AddIdentityCore之后添加此配置 builder.Services.ConfigureApplicationCookie(options => { options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.LoginPath = "/Identity/Account/Login"; options.AccessDeniedPath = "/Identity/Account/AccessDenied"; options.LogoutPath = "/Identity/Account/Logout"; options.SlidingExpiration = true; });
3. 简化Identity服务注册
你的AddIdentityCore注册已经包含必要的服务,无需手动添加AddSignInManager(AddIdentityCore会自动注册),可以保持现有代码,但确保顺序正确:
builder.Services.AddIdentityCore<myAppUser>(options => { // 你的Identity配置... }) .AddRoles<IdentityRole>() .AddDefaultUI() .AddEntityFrameworkStores<myAppIdentityContext>();
验证要点
- 确保登录页面(
/Identity/Account/Login)使用SignInManager.PasswordSignInAsync方法完成登录,且未指定非默认的Scheme。 - 登录后检查浏览器Cookie,确认存在名为
.AspNetCore.Identity.Application的Cookie(这是Identity默认的登录Cookie名称)。
内容的提问来源于stack exchange,提问作者Aequitas
相关产品推荐
相关产品推荐

