基于Azure AD认证的Azure App Service应用间隔访问返回401求助
针对你遇到的浏览器长期未关闭导致AAD认证Cookie过期后出现401的问题,可通过以下几种方案解决,实现自动处理过期Cookie、必要时引导重登:
1. 配置.NET Core认证中间件的自动刷新与Cookie清理
在Program.cs(.NET 6+)或Startup.cs(.NET 5及更早)中调整认证中间件的配置,让应用主动检测令牌过期并处理Cookie:
// 配置AAD认证 builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi() .AddInMemoryTokenCaches(); // 调整应用Cookie的行为 builder.Services.ConfigureApplicationCookie(options => { // 开启滑动过期:用户活跃时自动延长Cookie有效期 options.SlidingExpiration = true; // 设置Cookie有效期,匹配企业日常工作时长(比如8小时) options.ExpireTimeSpan = TimeSpan.FromHours(8); // 当需要跳转到登录页时,先清除过期的AppServiceAuthSession Cookie options.Events.OnRedirectToLogin = context => { context.Response.Cookies.Delete("AppServiceAuthSession", new CookieOptions { Domain = context.Request.Host.Host, Path = "/" }); context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }; // 验证用户主体时,检查令牌是否即将过期,触发重新认证 options.Events.OnValidatePrincipal = context => { if (context.Properties.ExpiresUtc.HasValue && context.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow.AddMinutes(5)) { // 标记主体无效,触发重新登录 context.RejectPrincipal(); } return Task.CompletedTask; }; });
2. 调整Azure App Service的认证会话设置
直接在Azure门户中配置App Service的认证会话参数,让平台自动管理Cookie生命周期:
- 进入App Service -> 左侧菜单「认证」 -> 选择你的AAD身份提供者 -> 点击「高级设置」
- 在「会话管理」区域:
- 设置「会话过期时间」为合适时长(如8小时)
- 勾选「允许滑动会话」,这样用户在活跃期间会自动延长会话有效期,避免过期后未刷新的问题
3. 前端全局拦截401错误并自动处理
如果应用包含前端交互(如Razor Pages、Blazor或SPA),可以通过全局脚本拦截401响应,自动清除过期Cookie并重定向登录:
document.addEventListener('DOMContentLoaded', function() { // 拦截XMLHttpRequest请求的401 const originalXhrOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url) { this.addEventListener('load', function() { if (this.status === 401) { clearAuthCookie(); redirectToLogin(); } }); originalXhrOpen.apply(this, arguments); }; // 拦截Fetch请求的401 const originalFetch = window.fetch; window.fetch = function(resource, options) { return originalFetch(resource, options) .then(response => { if (response.status === 401) { clearAuthCookie(); redirectToLogin(); } return response; }); }; // 处理页面加载时的401(如直接刷新过期页面) fetch(window.location.href, { credentials: 'include' }) .then(response => { if (response.status === 401) { clearAuthCookie(); redirectToLogin(); } }); // 清除AppServiceAuthSession Cookie function clearAuthCookie() { document.cookie = "AppServiceAuthSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=" + window.location.hostname; } // 重定向到AAD登录页,保留原路径 function redirectToLogin() { const redirectUri = encodeURIComponent(window.location.pathname + window.location.search); window.location.href = "/.auth/login/aad?post_login_redirect_uri=" + redirectUri; } });
4. 调整AAD应用的令牌生命周期
在Azure AD门户中延长令牌有效期,减少过期频率:
- 进入「应用注册」 -> 你的应用 -> 左侧菜单「令牌配置」
- 点击「添加配置」,设置ID令牌和访问令牌的「有效时长」(比如8小时)
- 启用「可刷新令牌」的滑动过期,确保用户活跃时能自动刷新令牌
内容的提问来源于stack exchange,提问作者wr125
相关产品推荐
相关产品推荐

