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

ASP.NET Core Identity Cookie认证失效问题求助

ASP.NET Core认证问题:登录成功但signInManager.IsSignedIn(User)始终返回false

我在为已完成的前端搭建ASP.NET Core后端时遇到认证异常:signInManager.IsSignedIn(User)与User.IsAuthorized始终返回false,且找不到AspNetCore.Cookies。登录时_signInManager.PasswordSignInAsync()返回成功,但首页的身份验证不通过。相关代码如下:

登录接口代码

[HttpPost("/confirm/login")]
public async Task<IActionResult> Login([FromForm] UserLoginningModel userModel, [FromServices] UserManagerServiceBase userManager)
{
    if (ModelState.IsValid)
    {
        var result = await userManager.LoginUserAsync(_mapper.Map<UserForLoginningDto>(userModel));

        if (result.Success)
        {
            return Redirect("/");
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error);
        }
    }

    return View(userModel);
}

自定义LoginUserAsync方法代码

public override async Task<AuthenticationResult> LoginUserAsync(UserForLoginningDto userDto)
{
    var result = await _signInManager.PasswordSignInAsync(userDto.UserName, userDto.Password, true, lockoutOnFailure: true);

    if (result.Succeeded)
    {
        return AuthenticationResult.SuccessResult;
    }

    if (result.IsLockedOut)
    {
        return new AuthenticationResult("This account is locked out");
    }
    else
    {
        return new AuthenticationResult("Invalid password or email");
    }
}

服务配置代码

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

services.AddDatabaseDeveloperPageExceptionFilter();

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

        options.LoginPath = new PathString("/login");
        options.AccessDeniedPath = new PathString("/Errors?status=404");
        options.SlidingExpiration = true;
    });

[...]

services.AddControllersWithViews();

中间件配置代码

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

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

问题原因及修复方案

1. 重复配置认证服务导致冲突

AddDefaultIdentity已经默认集成了Cookie认证,后续手动添加的AddAuthentication+AddCookie会覆盖或干扰默认配置,导致Cookie无法正确生成或读取。

修复:移除手动的认证配置,通过AddDefaultIdentity的扩展项配置Cookie:

services.AddDefaultIdentity<IdentityUser>(options => 
{
    options.SignIn.RequireConfirmedAccount = true;
    // 在这里统一配置Cookie参数
    options.Cookies.ApplicationCookie.HttpOnly = true;
    options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromMinutes(5);
    options.Cookies.ApplicationCookie.LoginPath = new PathString("/login");
    options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Errors?status=404");
    options.Cookies.ApplicationCookie.SlidingExpiration = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>();

2. 用户账户未完成验证

配置中开启了RequireConfirmedAccount = true,如果用户账户未完成邮箱/电话验证,即使登录成功,IsSignedIn也会返回false。

修复:

  • 测试阶段可暂时关闭验证要求:
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddEntityFrameworkStores<ApplicationDbContext>();
  • 或手动标记用户为已验证:
// 示例:在登录逻辑中添加验证标记
var user = await _userManager.FindByNameAsync(userDto.UserName);
await _userManager.SetEmailConfirmedAsync(user, true);

3. Cookie名称不匹配

默认AddDefaultIdentity使用的Cookie名称是.AspNetCore.Identity.Application,手动AddCookie生成的是.AspNetCore.Cookies,两者不匹配导致验证失败。按步骤1修复配置即可解决此问题。

内容的提问来源于stack exchange,提问作者Булат Хафизов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:35:15