Android 16上.NET 9 MAUI应用Google OAuth报401错误求助
解决Android 16(API 36)下MAUI WebAuthenticator登录跳转及401问题
1. 升级MAUI版本至兼容Android 16的稳定版
Android 16(API 36)带来了平台行为变更,旧版MAUI的WebAuthenticator实现未适配这些变化。请将项目升级至.NET MAUI 8.0.70或更高版本,该版本已针对API 36完成兼容性优化。
2. 调整WebAuthenticationCallbackActivity的IntentFilter配置
Android 16对导出Activity的Intent Filter规则更严格,需补充AutoVerify = true属性帮助系统正确识别跳转意图,同时确认配置无语法错误:
[Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop, Exported = true)] [IntentFilter( new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "myapp", DataHost = "callback", AutoVerify = true)] // 新增该属性 public class WebAuthenticationCallbackActivity : Microsoft.Maui.Authentication.WebAuthenticatorCallbackActivity { }
3. 修正后端Deep Link的格式
Android 16对URL参数解析更严格,需确保返回的链接完全符合RFC 3986标准:
- 所有参数值必须通过
Uri.EscapeDataString正确编码 - 替换URL中的
&为&(后端代码中&是HTML转义格式,实际URL需使用标准的&分隔参数)
修正后的后端代码:
const string callbackScheme = "myapp"; var finalDeepLink = $"{callbackScheme}://callback?access_token={Uri.EscapeDataString(stringToken)}&expires_in={expiresIn}"; var deepLink = $"{callbackScheme}://callback?error={Uri.EscapeDataString(errorCode)}";
4. 调整WebAuthenticator调用逻辑
在LoginViewModel.cs中添加Android平台专属配置,强制使用系统默认浏览器验证,规避WebView在Android 16下的权限兼容问题:
var authOptions = new WebAuthenticatorOptions { Url = new Uri(APIEndpoint + "/api/mobileauth/Google"), CallbackUrl = new Uri("myapp://callback"), #if ANDROID UsePreferredBrowser = true #endif }; var authResult = await WebAuthenticator.Default.AuthenticateAsync(authOptions);
5. 确认AndroidManifest权限配置
确保AndroidManifest.xml中添加必要权限,支持应用处理链接跳转:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
6. 排查401错误根源
401格式错误大概率是后端响应不符合OAuth 2.0规范导致,建议:
- 抓包查看完整响应内容,确认错误参数
error的格式、编码是否符合WebAuthenticator预期 - 检查组织邮箱登录时的请求头、参数是否因Android 16环境(如User-Agent差异)出现丢失或格式异常
内容的提问来源于stack exchange,提问作者BSB
相关产品推荐
相关产品推荐

