.NET Core 3.1控制台应用如何获取登录用户邮箱?
解决方案:从Azure AD账户或
az login令牌中获取用户邮箱 针对你的.NET Core 3.1控制台应用需求,我整理了两个实用方案,分别对应你提到的两种场景:
方案1:从系统登录的Azure AD账户直接获取邮箱
既然用户已经通过Azure AD账户登录Windows/Mac系统,我们可以借助系统原生的身份信息API来提取邮箱。
Windows平台实现
在Windows上,你可以使用System.DirectoryServices.AccountManagement库来获取当前用户的完整AD信息,包括邮箱。步骤如下:
- 安装NuGet包:
System.DirectoryServices.AccountManagement - 使用以下代码获取邮箱:
using System.DirectoryServices.AccountManagement; try { using (var context = new PrincipalContext(ContextType.Domain)) { var currentUser = UserPrincipal.Current; if (currentUser != null) { string userEmail = currentUser.EmailAddress; Console.WriteLine($"当前用户邮箱:{userEmail}"); } else { Console.WriteLine("无法获取当前用户信息"); } } } catch (Exception ex) { Console.WriteLine($"获取信息失败:{ex.Message}"); }
Mac平台实现
Mac上可以通过执行系统命令dscl来读取用户的邮箱信息,代码示例:
using System.Diagnostics; var process = new Process { StartInfo = new ProcessStartInfo { FileName = "/usr/bin/dscl", Arguments = ". -read /Users/" + Environment.UserName + " EMailAddress", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true } }; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); // 解析输出提取邮箱 if (!string.IsNullOrEmpty(output)) { var emailLine = output.Split('\n').FirstOrDefault(line => line.StartsWith("EMailAddress:")); if (emailLine != null) { string userEmail = emailLine.Split(':')[1].Trim(); Console.WriteLine($"当前用户邮箱:{userEmail}"); } }
方案2:从az login的缓存令牌中提取邮箱
如果你已经执行了az login,Azure CLI会将访问令牌缓存到本地文件中,我们可以读取这个文件并解码JWT令牌来获取邮箱信息。
步骤:
- 安装NuGet包:
System.IdentityModel.Tokens.Jwt(用于解码JWT) - 读取Azure CLI的令牌缓存文件:
- Windows路径:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azure", "accessTokens.json") - Mac/Linux路径:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azure", "accessTokens.json")
- Windows路径:
- 解析JSON并解码JWT提取邮箱:
using System; using System.IO; using System.Linq; using System.Text.Json; using System.IdentityModel.Tokens.Jwt; try { // 获取令牌缓存文件路径 string tokenFilePath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azure", "accessTokens.json" ); if (!File.Exists(tokenFilePath)) { Console.WriteLine("未找到Azure CLI令牌缓存文件,请先执行az login"); return; } // 读取并解析JSON string jsonContent = File.ReadAllText(tokenFilePath); var tokens = JsonSerializer.Deserialize<AzureCliToken[]>(jsonContent); // 取最新的有效令牌(可以根据需要筛选) var latestToken = tokens.OrderByDescending(t => t.ExpiresOn).FirstOrDefault(); if (latestToken == null) { Console.WriteLine("未找到有效令牌"); return; } // 解码JWT令牌 var handler = new JwtSecurityTokenHandler(); var jwtToken = handler.ReadJwtToken(latestToken.AccessToken); // 提取邮箱声明(通常是"email"或"upn"字段) string userEmail = jwtToken.Claims.FirstOrDefault(c => c.Type == "email" || c.Type == "upn")?.Value; if (!string.IsNullOrEmpty(userEmail)) { Console.WriteLine($"从az login令牌中获取的邮箱:{userEmail}"); } else { Console.WriteLine("令牌中未包含邮箱信息"); } } catch (Exception ex) { Console.WriteLine($"提取邮箱失败:{ex.Message}"); } // 用于反序列化的模型类 public class AzureCliToken { public string AccessToken { get; set; } public long ExpiresOn { get; set; } // 其他字段可以根据需要添加,比如TenantId等 }
注意事项:
- Azure CLI的令牌缓存路径可能会随版本变化,需要确保路径正确
- 解码JWT时,不需要验证签名(因为我们只是提取声明信息)
- 确保应用有读取
.azure文件夹的权限
内容的提问来源于stack exchange,提问作者Ashkan S
相关产品推荐
相关产品推荐

