Flutter InAppWebView打开原生应用失败:Azure AD B2C登录遇ERR_UNKNOWN_URL_SCHEME
解决Flutter应用中Azure AD B2C登录后otpauth链接打开失败的问题
一、Flutter InAppWebView与Android原生通信的可行性
完全可以实现。InAppWebView提供了多种与原生交互的方式,最常用的是URL拦截结合MethodChannel,或者通过JavaScript通道直接交互,下面结合你的问题给出具体解决方案。
二、解决otpauth链接打开失败的具体方案
方案1:拦截URL并使用url_launcher插件打开
WebView默认仅支持处理http/https协议,遇到otpauth://这类自定义Scheme会抛出ERR_UNKNOWN_URL_SCHEME错误。可以通过InAppWebView的URL拦截机制捕获这类链接,再用url_launcher插件调用系统能力打开对应应用:
- 先在
pubspec.yaml中添加依赖:
dependencies: url_launcher: ^6.1.12
- 在InAppWebView中添加拦截逻辑:
import 'package:url_launcher/url_launcher.dart'; InAppWebView( initialUrlRequest: URLRequest(url: Uri.parse("你的Azure AD B2C登录页面URL")), shouldOverrideUrlLoading: (controller, navigationAction) async { final uri = navigationAction.request.url!; // 拦截otpauth开头的链接 if (uri.scheme == 'otpauth') { if (await canLaunchUrl(uri)) { await launchUrl(uri, mode: LaunchMode.externalApplication); } // 返回CANCEL阻止WebView继续处理该链接 return NavigationActionPolicy.CANCEL; } // 其他链接正常交由WebView处理 return NavigationActionPolicy.ALLOW; }, )
方案2:通过MethodChannel与Android原生通信打开应用
如果不想依赖第三方插件,可直接通过MethodChannel调用Android原生代码打开Microsoft Authenticator:
Flutter端代码
import 'package:flutter/services.dart'; // 定义MethodChannel static const _otpChannel = MethodChannel('com.yourapp/otpauth'); InAppWebView( initialUrlRequest: URLRequest(url: Uri.parse("你的Azure AD B2C登录页面URL")), shouldOverrideUrlLoading: (controller, navigationAction) async { final uri = navigationAction.request.url!; if (uri.scheme == 'otpauth') { try { await _otpChannel.invokeMethod( 'openAuthenticator', {'url': uri.toString()}, ); } on PlatformException catch (e) { print('打开失败: ${e.message}'); } return NavigationActionPolicy.CANCEL; } return NavigationActionPolicy.ALLOW; }, )
Android原生端代码(MainActivity.kt)
import android.content.Intent import android.net.Uri import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { private val CHANNEL = "com.yourapp/otpauth" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> when (call.method) { "openAuthenticator" -> { val url = call.argument<String>("url") url?.let { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(it)) startActivity(intent) result.success(null) } ?: result.error("INVALID_URL", "URL不能为空", null) } else -> result.notImplemented() } } } }
方案3:调整Azure AD B2C的MFA配置(可选)
如果业务允许,可以在Azure门户中修改AD B2C的用户流,添加短信验证、邮件验证等不需要依赖Microsoft Authenticator的MFA方式,从根源上避免处理自定义Scheme链接的问题。
内容的提问来源于stack exchange,提问作者Naveen N
相关产品推荐
相关产品推荐

