ASP.NET Core中AddMicrosoftAccount获取UPN Claim返回null问题
解决ASP.NET Core中AddMicrosoftAccount无法获取UPN声明的问题
核心原因
普通个人微软账户(MSA,如outlook.com)本身不提供UPN声明,只有Azure AD工作/学校账户才包含该属性。另外,AddMicrosoftAccount默认配置不会自动请求或映射UPN,需要针对性调整。
解决方案分两种场景
场景1:仅针对Azure AD工作/学校账户
直接切换到Azure AD认证方案(而非通用微软账户):
- 安装NuGet包:
Microsoft.AspNetCore.Authentication.AzureAD.UI - 在Program.cs中配置Azure AD认证:
builder.Services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => builder.Configuration.Bind("AzureAd", options)); // 手动映射UPN声明,确保不被过滤 builder.Services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { options.ClaimActions.MapJsonKey(ClaimTypes.Upn, "upn"); }); - 配置文件(appsettings.json)中添加Azure AD参数:
"AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "your-domain.onmicrosoft.com", "TenantId": "your-tenant-id", "ClientId": "your-client-id", "CallbackPath": "/signin-oidc" }
场景2:同时支持个人MSA和工作/学校账户
如果必须用AddMicrosoftAccount,需要通过Graph API获取UPN(仅工作账户有效):
- 在Program.cs中添加Graph API的
User.Read权限:builder.Services.AddAuthentication() .AddMicrosoftAccount(options => { options.ClientId = builder.Configuration["Authentication:Microsoft:ClientId"]; options.ClientSecret = builder.Configuration["Authentication:Microsoft:ClientSecret"]; // 添加User.Read权限以获取用户详细信息 options.Scope.Add("User.Read"); }); - 在登录回调中,使用获取到的AccessToken调用Graph API获取UPN:
var loginInfo = await _signInManager.GetExternalLoginInfoAsync(); if (loginInfo != null) { // 获取Graph API的访问令牌 var accessToken = loginInfo.AuthenticationTokens.FirstOrDefault(t => t.Name == "access_token")?.Value; if (!string.IsNullOrEmpty(accessToken)) { using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me"); if (response.IsSuccessStatusCode) { var userData = await response.Content.ReadFromJsonAsync<Dictionary<string, object>>(); var upn = userData?.GetValueOrDefault("upn")?.ToString(); // 使用upn做后续处理 } } }
注意事项
- 个人MSA账户无论如何都不会返回UPN,若业务必须UPN,需限制仅允许Azure AD工作/学校账户登录。
- 在Azure应用注册中,确保已授予
User.Read权限并完成管理员/用户同意。
内容的提问来源于stack exchange,提问作者ydinesh
相关产品推荐
相关产品推荐

