浏览器/标签页关闭时终止用户会话的技术实现求助
浏览器/标签页关闭时终止IdentityServer4会话的解决方案
首先明确:offline_access是用来获取刷新令牌、实现长期离线访问的配置,和即时终止会话完全无关,你用错了配置项。下面是具体实现步骤:
前端监听页面关闭事件
在客户端应用中,监听beforeunload事件(页面关闭前触发,比unload更可靠),主动调用IdentityServer的结束会话端点:window.addEventListener('beforeunload', async () => { try { // 先清理本地存储的令牌 localStorage.removeItem('id_token'); localStorage.removeItem('access_token'); // 发起IS4登出请求 await fetch('https://your-identity-server-url/connect/endsession', { method: 'POST', credentials: 'include', // 携带IS4的会话Cookie headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ id_token_hint: localStorage.getItem('id_token'), // 提前存储的ID Token post_logout_redirect_uri: 'https://your-client-url/logout-callback' // 可选,登出后跳转地址 }) }); } catch (err) { // 网络异常不阻塞页面关闭,直接忽略 } });配置IdentityServer允许跨域请求(跨域场景)
如果客户端和IS4不在同一域名,需要在IS4中配置CORS,允许客户端域名访问/connect/endsession端点:services.AddCors(options => { options.AddPolicy("ClientCorsPolicy", policy => { policy.WithOrigins("https://your-client-domain") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); // 在Configure中启用CORS app.UseCors("ClientCorsPolicy");确保IS4会话Cookie为会话型
配置IS4的会话Cookie为会话Cookie(不设置过期时间),浏览器关闭时会自动清除该Cookie:services.AddAuthentication() .AddCookie(options => { options.Cookie.IsEssential = true; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; // 不要设置Expires或MaxAge,默认即为会话Cookie });客户端侧清理本地凭证
除了调用IS4登出,还要在页面关闭时清除本地存储的令牌(如localStorage/sessionStorage中的凭证),避免残留的令牌被滥用。
内容的提问来源于stack exchange,提问作者kabuto178
相关产品推荐
相关产品推荐

