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<client-id>://auth</client-id>
msauth.<bundle-id>://auth</bundle-id>(需在 Xcode 中配好 Bundle ID)msal<client-id>://auth</client-id>(并在 AndroidManifest.xml 声明 intent-filter)在 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);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 匹配、平台回调桥接到位。
以上就是MAUI怎么集成认证服务 MAUI MSAL登录教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号