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

ASP.NET+EF Core项目登录后10-15分钟认证失效问题求助

问题背景

我正在开发基于ASP.NET与EF Core的API,用户管理采用FirebaseAuth,登录/登出、声明式认证及授权检查的实现代码如下,目前遇到的问题是:登录后约10-15分钟,所有需授权的请求返回401 Unauthorized错误。测试接口显示刚登录时认证状态为true,一段时间后变为false,声明信息为空。已尝试配置SecurityStampValidatorOptions设置10小时验证间隔,但无效果。


登录/登出实现

public async Task<IResult> LogInUser(HttpContext context, string userCred, string password,
    LoginDeviceType deviceType)
{
    try
    {
        var user = await databaseUserProvider.GetUser(userCred);
        if (user == null)
            return Results.Problem(detail: "Cannot find user in database", statusCode: 500,
                title: "User not found");
        string userEmail = emailAttribute.IsValid(userCred) ? userCred : user.Email;

        var authLink = await firebaseAuthProvider.SignInWithEmailAndPasswordAsync(userEmail, password);

        await SignInUserV2(userCred, password, context);

        return Results.Ok(new { user.Id, user.DisplayName, authLink.FirebaseToken });
    }
    catch (Exception ex)
    {
        return Results.Problem(detail: ex.Message, statusCode: 500, title: "An error occurred while logging in");
    }
}    

public async Task<IResult> LogOutUser(HttpContext context)
{
    await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Results.Ok("User has been logged out successfully.");
}    

声明式认证实现

public async Task SignInUserV2(string username, string password, HttpContext httpContext)
{
    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, username),
        new Claim(ClaimTypes.Role, "User") 
    };
    var claimsIdentity = new ClaimsIdentity(
        claims,
        CookieAuthenticationDefaults.AuthenticationScheme); 
    var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
    await httpContext.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal,
        new AuthenticationProperties
        {
            IsPersistent = true, 
            ExpiresUtc = DateTime.UtcNow.AddDays(7) 
        });
}

用户认证检查逻辑

public override bool IsUserAuthorized(HttpContext httpContext)
{
    if (httpContext.User.Identity?.IsAuthenticated == true)
    {
        var username = httpContext.User.Identity.Name; 
        var roles = httpContext.User.FindAll(ClaimTypes.Role); 
        return true;
    }
    else
    {
        // User is not authenticated
        return false;
    }
 }

问题原因及解决方法

核心原因

  1. Cookie认证默认滑动过期限制:ASP.NET Core Cookie认证的默认滑动过期时间为15分钟,即便你在登录时设置了ExpiresUtc为7天,若用户15分钟内无活跃请求,Cookie会自动失效。
  2. SecurityStampValidator配置无效:你未使用ASP.NET Core Identity的SignInManager,而是手动创建ClaimsPrincipal,SecurityStampValidatorOptions仅对Identity管理的用户生效,因此该配置对你的场景起不到作用。

解决步骤

1. 全局配置Cookie认证参数

在Program.cs(或Startup.cs)中显式配置Cookie认证的有效期和滑动过期规则,覆盖默认值:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.SlidingExpiration = true; // 用户活跃时自动延长Cookie有效期
        options.ExpireTimeSpan = TimeSpan.FromDays(7); // 与登录时设置的ExpiresUtc保持一致
        options.Cookie.MaxAge = TimeSpan.FromDays(7); // 确保Cookie的最大存活期与有效期匹配
    });

2. 对齐登录时的认证属性配置

若已通过全局配置设置了ExpireTimeSpan,可移除SignInAsync中的AuthenticationProperties参数,让全局配置统一生效;若保留该参数,需确保ExpiresUtc与全局配置的ExpireTimeSpan一致,避免冲突。

3. 移除无效的SecurityStampValidator配置

由于你的认证逻辑未依赖ASP.NET Core Identity,直接删除SecurityStampValidatorOptions相关配置即可,避免混淆。

4. 验证配置效果

修改完成后,登录后保持15分钟以上不发起请求,再调用授权接口,检查认证状态是否仍为true、声明信息是否存在。若配置正确,认证状态将保持有效直到7天后的绝对过期时间。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:34:57