MAUI 集成认证服务基于 MSAL.NET 实现,利用平台原生能力(如 WebAuthenticator、ASWebAuthenticationSession、Chrome Custom Tabs)安全唤起登录页,自动处理重定向、令牌缓存与刷新;需在 Entra 管理中心注册应用并配置客户端 ID、租户 ID 及各平台重定向 URI;通过 NuGet 引入 Microsoft.Identity.Client,在 MauiProgram.cs 中注册 IPublicClientApplication;封装 AuthService 调用 AcquireTokenInteractive 登录、RemoveAsync 登出;iOS/Android 需重写 OpenUrl/OnNewIntent 传递回调;登录后可获取用户信息及令牌,推荐结合 AuthenticationStateProvider 与 AuthorizeView 实现权限控制。
MAUI 集成认证服务,核心是用 MSAL.NET(Microsoft Authentication Library)实现基于 Microsoft 标识平台(如 Azure AD、Entra ID 或 Azure AD B2C)的登录。它不依赖 WebView 手动拼接 URL,
而是通过平台原生能力(如 Windows 的 WebAuthenticator、iOS/macOS 的 ASWebAuthenticationSession、Android 的 Chrome Custom Tabs)安全唤起登录页,并自动处理重定向、令牌缓存与刷新。
在 Microsoft Entra 管理中心完成以下操作:
msal://auth
msauth.://auth (需在 Xcode 中配好 Bundle ID)msal://auth (并在 AndroidManifest.xml 声明 intent-filter)在 MAUI 主项目(.csproj)中添加 NuGet 包:
在 MauiProgram.cs 中注册 MSAL 公共客户端:
var clientId = "your-client-id";
var tenantId = "your-tenant-id";
var redirectUri = DeviceInfo.Platform switch
{
DevicePlatform.Windows => "msal" + clientId + "://auth",
DevicePlatform.iOS => "msauth.your.bundle.id://auth",
DevicePlatform.Android => "msal" + clientId + "://auth",
_ => throw new PlatformNotSupportedException()
};
var pca = PublicClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithRedirectUri(redirectUri)
.WithLogging((level, message, containsPii) =>
Debug.WriteLine($"MSAL: {level} - {message}"))
.Build();
builder.Services.AddSingleton(pca);
MAUI 使用 WebAuthenticator.Default.AuthenticateAsync() 启动系统浏览器流程,MSAL 会自动构造授权 URL 并监听回调:
AuthService),注入 IPublicClientApplication
AcquireTokenInteractive(),它内部会触发 WebAuthenticator
RemoveAsync(account) 清除本地缓存账号AppDelegate.cs 中重写 OpenUrl;Android 需在 MainActivity.cs 中重写 OnNewIntent,把回调传给 MSAL 处理登录成功后,MSAL 返回 AuthenticationResult,包含 ID Token 和访问令牌。你可以提取用户基本信息:
result.Account.Username(通常为邮箱)result.Account.Name(显示名)result.IdToken 可用于调用受保护 API(如 Microsoft Graph)AuthenticationStateProvider,配合 AuthorizeView 组件做 UI 权限控制基本上就这些。不需要手写 OAuth 流程,也不用管理 token 过期——MSAL 自动刷新。关键点在于注册正确、重定向 URI 匹配、平台回调桥接到位。