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

MAUI中获取完整UPN(含邮箱格式)的IAzClientContext::get_UserUpn等效方法

在MAUI中获取完整UPN的跨平台方案(等效IAzClientContext::get_UserUpn)

MAUI没有统一的跨平台API直接获取完整UPN(如xxx@email.com格式),需通过平台特定代码或跨平台身份认证库实现,以下是可行方案:

平台特定实现

Windows平台

使用Windows Runtime API(非Win32),无需依赖原生Win32库,符合MAUI架构:

#if WINDOWS
using Windows.System.UserProfile;

public async Task<string> GetUserUpnAsync()
{
    try
    {
        return await UserInformation.GetUserPrincipalNameAsync();
    }
    catch (UnauthorizedAccessException)
    {
        // 处理权限不足场景
        return string.Empty;
    }
}
#endif

注意:需在Windows项目的Package.appxmanifest中添加用户信息访问权限。

Android平台

通过AccountManager获取账号邮箱(通常对应UPN):

#if ANDROID
using Android.Content;
using Android.Accounts;

public string GetUserUpn()
{
    AccountManager accountManager = AccountManager.FromContext(Android.App.Application.Context);
    // 示例针对Google账号,可根据实际场景修改账号类型(如企业域账号)
    Account[] accounts = accountManager.GetAccountsByType("com.google");
    return accounts.Length > 0 ? accounts[0].Name : string.Empty;
}
#endif

注意:需在Android项目的AndroidManifest.xml中添加GET_ACCOUNTS或READ_CONTACTS权限(依Android版本而定)。

iOS/macOS平台

通过Apple ID授权获取邮箱,或适配企业身份提供商的SDK:

#if IOS || MACCATALYST
using AuthenticationServices;

public async Task<string> GetUserUpnAsync()
{
    var provider = new ASAuthorizationAppleIDProvider();
    var credentialState = await provider.GetCredentialStateAsync(ASAuthorizationAppleIDProvider.GetDefaultUserIdentifier());
    
    if (credentialState == ASAuthorizationCredentialState.Authorized)
    {
        var request = new ASAuthorizationAppleIDRequest { RequestedScopes = new[] { ASAuthorizationScope.Email } };
        var controller = new ASAuthorizationController(new[] { request });
        // 需实现ASAuthorizationControllerDelegate回调获取邮箱,此处为简化示例
        // 若为企业账号,推荐使用MSAL库(见下文)
    }
    return string.Empty;
}
#endif

跨平台通用推荐方案:使用MSAL库

微软官方的Microsoft.Identity.Client(MSAL)是跨平台身份认证库,支持MAUI全平台,可直接获取完整UPN:

  1. 安装NuGet包:Microsoft.Identity.Client
  2. 实现代码:
using Microsoft.Identity.Client;

public async Task<string> GetUserUpnUsingMsalAsync()
{
    var app = PublicClientApplicationBuilder.Create("你的应用客户端ID")
        .WithRedirectUri($"msal{你的应用客户端ID}://auth")
        .Build();

    var accounts = await app.GetAccountsAsync();
    if (accounts.Any())
    {
        var result = await app.AcquireTokenSilent(new[] { "User.Read" }, accounts.First())
            .ExecuteAsync();
        return result.Account.Username;
    }
    else
    {
        // 无已登录账号时发起交互式登录
        var result = await app.AcquireTokenInteractive(new[] { "User.Read" })
            .ExecuteAsync();
        return result.Account.Username;
    }
}

该方案获取的Username即为完整UPN,完全等效于IAzClientContext::get_UserUpn的功能,且完全符合MAUI跨平台目标。

关于之前尝试方案的说明

System.Security.Principal.WindowsIdentity.GetCurrent().Name返回DOMAIN\Username格式,并非UPN;WindowsIdentity(userToken)需依赖包含UPN信息的有效token,若无正确配置则无法获取完整UPN,因此不适用于需求场景。

内容的提问来源于stack exchange,提问作者Marc George

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:25:28