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

如何在Azure AD认证的ASP.NET Core MVC 3.1.27中处理会话超时

ASP.NET Core MVC 3.1 + Azure AD 实现5分钟无活动自动登出

针对Azure AD认证场景,单纯配置Session不足以实现自动登出,需要结合Cookie认证的滑动过期机制和活动跟踪来实现,以下是具体步骤:

1. 配置Cookie认证参数

在ConfigureServices方法中,为Azure AD认证绑定Cookie选项,设置过期时间、滑动过期,并添加活动验证逻辑:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options))
    .AddCookie(options =>
    {
        // 设置5分钟无活动过期
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
        // 开启滑动过期:用户有活动则重置过期时间
        options.SlidingExpiration = true;
        // 自定义验证逻辑,检查用户活动状态
        options.Events = new CookieAuthenticationEvents
        {
            OnValidatePrincipal = context =>
            {
                var lastActivityStr = context.Properties.GetTokenValue("LastActivity");
                if (DateTimeOffset.TryParse(lastActivityStr, out var lastActivity))
                {
                    // 超过5分钟无活动则拒绝当前凭证并登出
                    if (DateTimeOffset.UtcNow - lastActivity > TimeSpan.FromMinutes(5))
                    {
                        context.RejectPrincipal();
                        return context.SignOutAsync(AzureADDefaults.AuthenticationScheme);
                    }
                }
                // 更新最新活动时间
                context.Properties.UpdateTokenValue("LastActivity", DateTimeOffset.UtcNow.ToString());
                return Task.CompletedTask;
            }
        };
    });

2. 正确配置Session服务

保持你已有的Session配置,确保IdleTimeout和过期时间一致:

services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(5);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

3. 调整中间件顺序

在Configure方法中,必须保证中间件的正确执行顺序,Session要放在认证授权之后、端点路由之前,同时添加一个中间件跟踪用户活动:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

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

    app.UseRouting();

    // 认证、授权中间件必须在Session之前
    app.UseAuthentication();
    app.UseAuthorization();

    // 启用Session
    app.UseSession();

    // 每次请求时更新用户活动标记
    app.Use(async (context, next) =>
    {
        if (context.User.Identity.IsAuthenticated)
        {
            context.Session.SetString("LastActivity", DateTime.UtcNow.ToString());
        }
        await next();
    });

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

注意事项

  • 生产环境中,务必将Cookie的Secure属性设为true,确保仅通过HTTPS传输
  • 若前端有AJAX请求,需确保这些请求也能触发活动时间更新,避免误登出
  • 验证appsettings.json中的Azure AD配置(ClientId、TenantId等)是否正确,确保认证流程正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:20:56