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

Asp.net Azure AD认证约1小时后Request.IsAuthenticated变为false需重选账号

Asp.net对接Azure AD登录1小时后Request.IsAuthenticated自动变为false需重新登录问题

我在使用Asp.net对接Azure AD实现身份认证时,遇到登录约1小时后Request.IsAuthenticated就被设置为false、需要用户重新选择账号登录的问题,已自行排查无果,特此咨询解决方案。

我已经检查了Web.config文件内的所有配置项,确认配置正确无误。相关登录方法代码如下:

public async Task SignIn()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
 }

我也尝试了同类问题的已知解决方案,依然未能解决该问题,我尝试添加的相关配置如下:

<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
</system.webServer>

我是完全参照Azure官方的Asp.net Web应用代码示例实现的。
相关配图


解决方案

这个问题核心是Azure AD颁发的ID令牌默认有效期为1小时,且当前配置没有启用令牌刷新机制、也没有调整Cookie会话有效期匹配令牌生命周期导致的,按以下步骤修改即可:

  1. 配置OpenID Connect中间件启用刷新令牌
    在你的OWIN Startup类的OpenIdConnectAuthenticationOptions配置中,添加ResponseType = "code id_token",设置UseTokenLifetime = false,同时开启Cookie滑动过期:
app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        // 原有其他配置保持不变
        ResponseType = "code id_token",
        UseTokenLifetime = false,
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthorizationCodeReceived = async n =>
            {
                var code = n.Code;
                var cca = ConfidentialClientApplicationBuilder
                    .Create(ClientId)
                    .WithClientSecret(ClientSecret)
                    .WithAuthority(Authority)
                    .WithRedirectUri(RedirectUri)
                    .Build();
                var result = await cca.AcquireTokenByAuthorizationCode(Scopes, code).ExecuteAsync();
                // 缓存刷新令牌,用于后续静默刷新身份
                n.AuthenticationTicket.Identity.AddClaim(new Claim("refresh_token", result.RefreshToken));
            }
        }
    });

// 调整Cookie认证配置
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromHours(24), // 可根据业务需求调整会话最长有效期
    CookieHttpOnly = true,
    CookieSecure = CookieSecureOption.Always
});
  1. 移除冲突的FormsAuthentication配置
    你添加的FormsAuthentication模块配置完全不需要,Azure AD OIDC认证不依赖Forms认证模块,直接删除Web.config中对应的<system.webServer/modules>下的FormsAuthentication相关配置即可,避免模块冲突导致的身份状态异常。
  2. 可选调整Azure AD令牌有效期
    如果有特殊业务需求,可在Azure AD门户对应应用注册的「令牌配置」页面,修改ID令牌的默认有效期,最长可设置为24小时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:04