You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8独立账户模板认证异常:SignInManager.IsSignedIn始终返回false

解决ASP.NET Core MVC中SignInManager.IsSignedIn(User)始终返回false的问题

核心问题:认证类型与配置不匹配

你自定义登录时使用了自定义认证类型(如"UserAuthenticated"),但默认的独立账户模板依赖Identity Cookie认证方案,其默认Scheme为IdentityConstants.ApplicationScheme(对应字符串"Identity.Application")。SignInManager会默认基于该Scheme验证登录状态,两者不匹配就会导致无法识别已登录用户。

解决方案步骤

1. 让ClaimsIdentity使用正确的认证类型

在SetUser方法中创建ClaimsIdentity时,直接使用Identity默认的认证Scheme,不要自定义未配置的类型:

using Microsoft.AspNetCore.Identity;

private ClaimsIdentity SetUser(string userId, string email)
{
    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.NameIdentifier, userId), // 关键Claim:SignInManager识别用户的核心标识
        new Claim(ClaimTypes.Email, email),
        // 按需添加其他业务所需Claim
    };

    // 使用Identity默认认证类型,确保与后续验证逻辑匹配
    return new ClaimsIdentity(claims, IdentityConstants.ApplicationScheme);
}

2. 正确调用HttpContext.SignInAsync

登录验证通过后,调用SignInAsync时指定对应的Scheme(或确保它是系统默认Scheme):

// AWS验证通过后生成ClaimsPrincipal
var claimsIdentity = SetUser(awsUserId, awsUserEmail);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

// 使用Identity默认Scheme完成登录,同时可配置持久化选项
await HttpContext.SignInAsync(
    IdentityConstants.ApplicationScheme,
    claimsPrincipal,
    new AuthenticationProperties
    {
        IsPersistent = true, // 可选:是否保持登录状态(记住我)
        ExpiresUtc = DateTimeOffset.UtcNow.AddDays(7) // 可选:设置登录有效期
    });

3. 确认Program.cs中的认证配置

确保Identity服务配置未修改默认的Cookie Scheme,默认模板配置如下(无需额外自定义Scheme,除非有特殊需求):

var builder = WebApplication.CreateBuilder(args);

// 添加默认Identity服务,自动绑定Cookie认证
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

// 可选:自定义Cookie行为(如登录/登出路径)
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Logout";
    options.AccessDeniedPath = "/Account/AccessDenied";
});

var app = builder.Build();

// 中间件顺序必须正确:先认证,后授权
app.UseAuthentication();
app.UseAuthorization();

// 其他中间件配置...
app.Run();

4. 验证视图中的判断逻辑

确保_LoginPartial.cshtml中的判断逻辑正确调用SignInManager.IsSignedIn(User):

@inject SignInManager<IdentityUser> SignInManager

@if (SignInManager.IsSignedIn(User))
{
    <!-- 已登录用户展示内容 -->
}
else
{
    <!-- 未登录用户展示内容 -->
}

额外排查点

  • 检查浏览器是否接收到Identity的Cookie(F12 → 应用程序 → Cookie),若未收到,说明SignInAsync调用存在问题。
  • 确认ClaimsIdentity中包含NameIdentifier Claim,这是SignInManager识别用户的必要条件。
  • 若确实需要自定义认证类型,需在Program.cs中注册对应的认证方案(如自定义Cookie方案),但无特殊需求不建议这么做,会增加复杂度。

内容的提问来源于stack exchange,提问作者Diego Perez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:57:30