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

如何从Azure.Identity获取Visual Studio登录关联的用户凭证值

我已通过手动输入邮箱、密码的方式将Visual Studio连接到Azure Active Directory,该凭证可在Visual Studio「工具」选项下的Azure Service Authenticator中查看。我需要获取与该凭证关联的ID,查阅相关官方文档后,希望获取与当前登录ID绑定的AZURE_USERNAME,但暂未找到获取该值的可行方法。特此咨询:是否只有主动显式设置该值才能获取到?另外,是否有方法可以获取Visual Studio当前登录用户或是Windows当前登录用户的邮箱ID,而非仅用户名?


问题1:是否只有主动显式设置才能获取AZURE_USERNAME?

是。AZURE_USERNAME是EnvironmentCredential专门读取的环境变量参数,Visual Studio的Azure认证逻辑不会自动将登录账号信息写入系统或进程的环境变量中,只有你主动在系统环境变量、项目启动配置、进程上下文里手动设置该参数后,才能通过环境变量读取接口获取到对应值。

问题2:获取Visual Studio/Windows当前登录用户的邮箱ID的方法

1. 获取Visual Studio当前登录的Azure账号邮箱

你可以配合Azure.Identity库的VisualStudioCredential调用Microsoft Graph接口直接拉取当前登录账号的信息,返回结果中的userPrincipalName字段就是你要的邮箱格式ID,参考实现代码如下:

using Azure.Identity;
using System.Net.Http.Headers;
using System.Text.Json.Serialization;

// 初始化VS凭证,可按需指定租户ID
var vsCredential = new VisualStudioCredential(new VisualStudioCredentialOptions
{
    TenantId = "<你的Azure租户ID,非必填>"
});

// 申请Graph接口访问令牌
var tokenResult = await vsCredential.GetTokenAsync(new Azure.Core.TokenRequestContext(
    new[] { "https://graph.microsoft.com/.default" }));

// 调用拉取当前用户信息
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.Token);
var res = await client.GetAsync("https://graph.microsoft.com/v1.0/me");
res.EnsureSuccessStatusCode();
var userInfo = await res.Content.ReadFromJsonAsync<GraphUser>();
var loginEmail = userInfo?.UserPrincipalName;

public class GraphUser
{
    [JsonPropertyName("userPrincipalName")]
    public string UserPrincipalName { get; set; }
}

2. 获取Windows当前登录用户的邮箱ID

如果你的Windows登录账号已加入/注册到Azure AD,有两种常用方式获取:

  • 同上使用Azure.Identity库的AzureCliCredential、InteractiveBrowserCredential调用Graph接口拉取信息
  • 读取系统注册表路径HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Identity\Identities下的缓存账户信息(仅适用于有Office登录记录的设备),也可调用NetUserGetInfo系统API搭配AD查询获取对应用户的UPN(用户主体名称,即邮箱格式ID)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 16:45:04