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会话有效期匹配令牌生命周期导致的,按以下步骤修改即可:
- 配置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 });
- 移除冲突的FormsAuthentication配置
你添加的FormsAuthentication模块配置完全不需要,Azure AD OIDC认证不依赖Forms认证模块,直接删除Web.config中对应的<system.webServer/modules>下的FormsAuthentication相关配置即可,避免模块冲突导致的身份状态异常。 - 可选调整Azure AD令牌有效期
如果有特殊业务需求,可在Azure AD门户对应应用注册的「令牌配置」页面,修改ID令牌的默认有效期,最长可设置为24小时。
内容的提问来源于stack exchange,提问作者Falgun
相关产品推荐
相关产品推荐

