Skip to content
maui-authentication logo

.NET MAUI Authentication

maui-authentication

Add authentication to .NET MAUI apps. Covers WebAuthenticator for generic OAuth 2.0 / social login, and MSAL.NET for Microsoft Entra ID (Azure AD) with broker support (Microsoft Authenticator), token caching, Conditional Access, platform-specific setup (Android, iOS, Windows), DelegatingHandler f...

SKILL.md

Full skill instructions

.NET MAUI Authentication

Security: Never Embed Secrets

❌ Never embed client secrets, API keys, or signing keys in a mobile app binary. They can be extracted trivially via decompilation.

The correct pattern:

  1. App calls WebAuthenticator pointing to your server endpoint
  2. Server initiates the OAuth flow with the identity provider (holds the client secret)
  3. Provider redirects back to your server with an auth code
  4. Server exchanges the code for tokens and returns them to the app via the callback URI

WebAuthenticator Gotchas

⚠️ Windows WebAuthenticator is broken

Windows WebAuthenticator is currently broken. See dotnet/​maui#2702. Use MSAL or a WinUI-specific workaround for Windows auth flows.

⚠️ Apple Sign In returns name/​email only once

Apple only returns the user's name and email on the first sign-in. Cache them immediately — subsequent sign-ins won't include them.

⚠️ PrefersEphemeralWebBrowserSession

Set to true on iOS 13+ to force a fresh login prompt. When false (default), the auth session shares cookies with Safari — the user may be auto-logged in, which can confuse logout/​switch-account flows.

⚠️ Callback URI mismatches

The most common auth failure is a URI scheme mismatch. The CallbackUrl in code must exactly match:

  • Android: DataScheme + DataHost in the IntentFilter
  • iOS: CFBundleURLSchemes in Info.plist
  • Windows: Protocol Name in Package.appxmanifest

WebAuthenticator Checklist

  • Callback URI scheme matches across all platform configs and CallbackUrl
  • Android has WebAuthenticatorCallbackActivity with correct IntentFilter
  • Android 11+ has <queries> for Custom Tabs in the manifest
  • iOS/​Mac Catalyst has CFBundleURLTypes in Info.plist
  • Client secrets are on the server, not in the app
  • Tokens stored with SecureStorage, cleared on logout
  • TaskCanceledException handled gracefully in UI

Choosing Between WebAuthenticator and MSAL.NET

CriteriaWebAuthenticatorMSAL.NET
Identity providerAny OAuth 2.0 / OIDCMicrosoft Entra ID
Broker support (SSO)❌ No✅ Microsoft Authenticator, Company Portal
Conditional Access / MFA❌ Manual✅ Built-in
Token cache & refresh❌ Manual (SecureStorage)✅ Automatic
ComplexitySimpleMore setup
Use whenGoogle, Apple, generic OIDCEntra ID / Azure AD, Microsoft Graph

MSAL.NET Gotchas

⚠️ Android: OnActivityResult is required

Forgetting AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs in MainActivity.OnActivityResult causes auth to hang silently after the browser returns.

⚠️ iOS: Keychain sharing is required

Without Entitlements.plist containing keychain group com.microsoft.adalcache, token caching fails silently and users are prompted to sign in every time.

⚠️ Handle MsalUiRequiredException

When AcquireTokenSilent throws MsalUiRequiredException, the cached token is expired and interaction is needed. Always fall back to AcquireTokenInteractive.

// ❌ Ignoring MsalUiRequiredException — user gets a crash
var result = await _pca.AcquireTokenSilent(scopes, account).ExecuteAsync(ct);

// ✅ Fall back to interactive when silent fails
try
{
    result = await _pca.AcquireTokenSilent(scopes, account).ExecuteAsync(ct);
}
catch (MsalUiRequiredException)
{
    result = await _pca.AcquireTokenInteractive(scopes).ExecuteAsync(ct);
}

⚠️ Handle user cancellation gracefully

// ✅ Don't treat cancellation as an error
catch (MsalClientException ex) when (ex.ErrorCode == "authentication_canceled")
{
    return null;  // User cancelled — not an error
}

⚠️ Blazor Hybrid: Auth happens at the MAUI layer

In MAUI Blazor Hybrid apps, authentication must happen at the MAUI layer (MSAL.NET), not in the Blazor WebView. Don't use AddMicrosoftIdentityWebApp or server-side OIDC patterns. Instead:

  1. MAUI handles sign-in via IAuthService (MSAL.NET)
  2. A custom MsalAuthenticationStateProvider exposes auth state to Blazor
  3. HttpClient with DelegatingHandler attaches bearer tokens automatically

MSAL.NET Checklist

  • Microsoft.Identity.Client NuGet package added
  • App registration created in Entra ID with correct redirect URIs
  • AuthConfig / appsettings.json has ClientId, TenantId, Scopes
  • Android: AndroidManifest.xml has <queries> for broker and browsers
  • Android: MainActivity.OnActivityResult calls AuthenticationContinuationHelper
  • iOS: Info.plist has CFBundleURLSchemes with msauth.{BundleId}
  • iOS: Entitlements.plist has keychain group com.microsoft.adalcache
  • iOS: AppDelegate.OpenUrl calls AuthenticationContinuationHelper
  • IAuthService registered as singleton in DI
  • DelegatingHandler attached to HttpClient for API calls
  • Login/​logout UI wired up
  • MsalUiRequiredException handled (triggers interactive sign-in)
  • MsalClientException with authentication_canceled handled gracefully

More Security skills

supabase logo
Security

supabase

Handles the full Supabase workflow from schema changes to deployment, with built-in security guardrails that catch common traps like RLS...

2.7K 308.9K
View

Comprehensive guides and best practices for Neon Serverless Postgres, covering setup, connection methods, authentication, and platform APIs.

98 216.2K
View

Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.

462 163.8K
View

A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust.

462 127.7K
View

Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security.

462 125.1K
View

Complete Better Auth server and client setup with database adapters, session management, plugins, and security configuration.

222 118.2K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View
cloudflare logo
Security

cloudflare

Complete Cloudflare platform integration with decision trees for compute, storage, AI, networking, security, and infrastructure-as-code.

3K 110.7K
View

Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.

253 103K
View
gws-gmail logo
Security

gws-gmail

Send, read, and manage Gmail messages, drafts, labels, and account settings.

31.2K 78.9K
View

Comprehensive website auditing across 230+ rules in 21 categories including SEO, performance, security, and accessibility.

94 72.3K
View
gws-shared logo
Security

gws-shared

Shared authentication, CLI syntax, and output formatting patterns for gws Google Workspace commands.

31.2K 63.4K
View

Security AI tools

StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
GeoSpy logo
Security

GeoSpy

GeoSpy: Pricing, Features, FAQs, and Alternatives for AI Teams

Free
View

Detect AI-generated voices to protect against audio fraud.

Paid
View

Ensure Your Content's Originality with AI Plagiarism Checker

Freemium
View
Img Upscaler logo
Security

Img Upscaler

Upscale images by 400% without quality loss

Freemium
View
AICheatCheck logo
Security

AICheatCheck

Accurately Detect AI-Generated Content with TheChecker.AI

Free
View
D
Security

Detect GPT

Chrome extension that detects and flags AI-generated content

Free
View