MAUI怎么集成认证服务 MAUI MSAL登录教程

来源:这里教程网 时间:2026-02-21 17:34:59 作者:

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 管理中心完成以下操作:

注册新应用,选择“单页应用”或“公共客户端(移动/桌面)”类型(不要选“Web”,除非你托管后端) 记录关键值:应用程序(客户端)ID、目录(租户)ID 为每个目标平台添加重定向 URI: Windows:
msal<client-id>://auth</client-id>
iOS/macOS:
msauth.<bundle-id>://auth</bundle-id>
(需在 Xcode 中配好 Bundle ID)
Android:
msal<client-id>://auth</client-id>
(并在 AndroidManifest.xml 声明 intent-filter)

安装 MSAL.NET 并初始化客户端

在 MAUI 主项目(.csproj)中添加 NuGet 包:

<PackageReference Include="Microsoft.Identity.Client" Version="4.62.2" />

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()
};
<p>var pca = PublicClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithRedirectUri(redirectUri)
.WithLogging((level, message, containsPii) =>
Debug.WriteLine($"MSAL: {level} - {message}"))
.Build();</p><p>builder.Services.AddSingleton(pca);

封装登录/登出逻辑并调用 WebAuthenticator

MAUI 使用

WebAuthenticator.Default.AuthenticateAsync()
启动系统浏览器流程,MSAL 会自动构造授权 URL 并监听回调:

创建一个服务类(如
AuthService
),注入
IPublicClientApplication
登录方法中调用
AcquireTokenInteractive()
,它内部会触发
WebAuthenticator
登出调用
RemoveAsync(account)
清除本地缓存账号
注意:iOS 需在
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 匹配、平台回调桥接到位。

相关推荐