使用DeviceCodeCredential时,Azure身份应用如何实现程序化登出?
问题描述
我之前通过以下代码实现应用登出:
public async Task<bool> SignOut() { var accounts = await PublicClientApp.GetAccountsAsync(); if (accounts.Any()) { try { await PublicClientApp.RemoveAsync(accounts.FirstOrDefault()); return true; } catch (MsalException ex) { _logger.Error(ex); Console.WriteLine("SignOut: See error log."); return false; } } return false; }
但现在我使用的是DeviceCodeCredential.AuthenticationRecord,不再有account对象,请问触发用户登出的最简单方法是什么?
解决方案
使用DeviceCodeCredential时,登出核心要完成两个操作:清除本地缓存的认证记录,以及可选的浏览器端Azure AD会话登出。
具体实现代码
- 清除本地缓存的认证记录
你需要提前保存好认证成功时获取的AuthenticationRecord,登出时通过它定位并清除对应缓存:
using Azure.Identity; using System.Threading.Tasks; public async Task<bool> SignOut(AuthenticationRecord authRecord) { if (authRecord == null) { return false; } try { // 配置缓存选项,需和初始化DeviceCodeCredential时的设置完全一致 var cacheOptions = new TokenCachePersistenceOptions { Name = "你的应用缓存标识" }; // 初始化Credential并清除指定记录的缓存 var credential = new DeviceCodeCredential(options => { options.TokenCachePersistenceOptions = cacheOptions; options.ClientId = "你的客户端ID"; options.TenantId = "你的租户ID"; // 其他和认证时一致的配置项 }); await credential.RemoveTokenCacheAsync(authRecord); return true; } catch (Exception ex) { _logger.Error(ex); Console.WriteLine("SignOut: 查看错误日志"); return false; } }
- (可选)触发浏览器端登出
如果需要让用户彻底退出Azure AD的全局会话,可以添加以下代码:
// 构造登出URL,替换为你的租户ID和回调地址 var logoutUrl = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/logout?post_logout_redirect_uri={Uri.EscapeDataString("你的应用回调地址")}"; // 打开浏览器完成登出 System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(logoutUrl) { UseShellExecute = true });
关键注意事项
TokenCachePersistenceOptions.Name必须和初始化DeviceCodeCredential时的设置一致,否则无法匹配到目标缓存。RemoveTokenCacheAsync是Azure Identity较新版本提供的方法,若使用旧版本,可手动清理默认缓存目录:Windows为%LOCALAPPDATA%\.IdentityService,macOS为~/Library/Application Support/.IdentityService,Linux为~/.local/share/.IdentityService。
内容的提问来源于stack exchange,提问作者Andrew Truckle
相关产品推荐
相关产品推荐

