MAUI Android Cognito 回调卡住:WebAuthenticator 未返回
结论:checkpoint 2 没有命中,通常说明 WebAuthenticator.Default.AuthenticateAsync(...) 的 await 没有完成。先要查的是 OAuth 回调有没有从浏览器正确送回 Android 应用;此时 Cognito 登录成功和后续 token 交换都还没有真正开始。最常见的原因是下面三处不一致:redirect_uri、Cognito App client 的 Allowed callback URLs、AndroidManifest 中接收回调的 intent-filter。也可能是回调 Activity 没有正确接收或转交 Intent。VS 调试器在浏览器打开后断开,多半是 Activity 或进程切换导致调试会话 detach,并不代表应用崩溃。
1. 先对齐三处 redirect_uri
把下面三处当成同一个字符串逐字核对,大小写、scheme、host、路径和结尾斜杠都要看:
- Cognito App client 的 Allowed callback URLs;
- MAUI 代码里的
redirectUri; - AndroidManifest 中
<data android:scheme="..." android:host="..." />。
自定义 scheme 示例:
<!-- 假设 redirectUri = "myapp://callback" -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="callback" />
</intent-filter>
这个 filter 要放在实际接收回调的 Activity 上。Android 12+ 上带 intent-filter 的 Activity 还要检查 android:exported 是否符合要求;如果用了 MAUI/Xamarin 的 WebAuthenticatorCallbackActivity 约定,确认它没有被删掉或改错。MainActivity 的 launchMode 和重写的 OnNewIntent 也要检查,避免回调 Intent 被消费后没有交给 WebAuthenticator。
2. 用 adb 验证回调是否真的进入应用
先别只看浏览器页面,手动模拟一次回调:
adb shell am start -a android.intent.action.VIEW -d "myapp://callback?code=test&state=test"
如果系统没有拉起应用,问题多半在 manifest 的 scheme/host 或 Activity 注册。能拉起应用但 checkpoint 2 仍不执行,就检查回调 Activity、OnNewIntent 和 WebAuthenticator 的注册、继承逻辑。复现时用 adb logcat 查看 ActivityNotFoundException、SecurityException、Intent 重复投递等信息,比依赖 VS 调试器更可靠。
3. 检查授权 URL 和调试方式
redirect_uri 在请求里必须经过 Uri.EscapeDataString,并且与注册值完全一致。示例:
var redirectUri = "myapp://callback"; // 与 Cognito 和 AndroidManifest 完全一致
var authorizeUrl =
$"{cognitoDomain}/oauth2/authorize" +
$"?client_id={Uri.EscapeDataString(clientId)}" +
"&response_type=code" +
$"&scope={Uri.EscapeDataString("openid email phone custom-scope")}" +
$"&redirect_uri={Uri.EscapeDataString(redirectUri)}" +
$"&state={Uri.EscapeDataString(state)}" +
$"&code_challenge={Uri.EscapeDataString(codeChallenge)}" +
"&code_challenge_method=S256";
prompt=login 只能用于测试,不能修好回调问题。Cognito 登录成功后,如果浏览器仍停在原页或回到登录页,先排查回调链路。关闭模拟器后再次登录能成功,这通常与首次启动时的 Activity 栈、自定义 Tab/浏览器状态或调试器切换有关。可以清应用数据、卸载重装,然后在不挂 VS 调试器的情况下用 logcat 复现,把配置问题和调试器干扰分开。
注意事项
- 不要只改 Cognito 控制台,也不要只改客户端代码,三处
redirect_uri必须同步。 - 不要把客户端密钥放进移动应用;移动端使用授权码 + PKCE 时,按 Cognito App client 的公开客户端配置处理。
- 如果使用
http/https回调,需要正确配置 App Links/Asset Links;调试阶段优先用自定义 scheme 验证回调。 - 回调能进入应用后,再检查 token 交换时的
client_id、code_verifier和redirect_uri是否与授权请求一致。
按这个顺序排查,一般能定位到“浏览器已登录但应用收不到回调”的具体环节。checkpoint 2 恢复执行后,才会走到用 code 换 token 的阶段。
备注:内容仅供参考。
