Flutter中如何获取认证服务重定向URL查询参数中的Token(无需服务器)
Flutter中获取认证重定向URL的查询参数(无需服务器方案)
核心结论
完全不需要搭建服务器,通过配置自定义URL Scheme(或iOS Universal Links/Android App Links),配合插件监听App的唤醒事件,就能直接获取重定向URL中的Token、用户ID等查询参数。
实现步骤
1. 添加依赖
在pubspec.yaml中引入所需插件:
dependencies: flutter: sdk: flutter url_launcher: ^6.2.5 # 用于启动认证服务链接 uni_links: ^0.5.1 # 用于监听App的URL唤醒事件
2. 配置平台自定义URL Scheme
让系统识别哪些URL需要跳转到你的App:
Android端
修改android/app/src/main/AndroidManifest.xml,在主Activity标签内添加以下intent-filter:
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 自定义Scheme和Host,可按需修改 --> <data android:scheme="myapp" android:host="auth" /> </intent-filter>
iOS端
修改ios/Runner/Info.plist,添加URL类型配置:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>myapp</string> <!-- 自定义Scheme --> </array> <key>CFBundleURLName</key> <string>auth</string> <!-- 自定义Host --> </dict> </array>
3. 实现代码逻辑
通过uni_links监听URL唤醒事件,解析查询参数:
import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:uni_links/uni_links.dart'; void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String? _token; String? _userId; @override void initState() { super.initState(); _setupLinkListener(); } // 配置URL监听 Future<void> _setupLinkListener() async { // 监听App运行时被URL唤醒的事件 uriLinkStream.listen((Uri? uri) { _parseUri(uri); }, onError: (err) { // 处理监听错误 }); // 检查App启动时是否来自URL跳转 final initialUri = await getInitialUri(); _parseUri(initialUri); } // 解析Uri中的查询参数 void _parseUri(Uri? uri) { if (uri != null && uri.host == 'auth') { setState(() { _token = uri.queryParameters['token']; _userId = uri.queryParameters['user_id']; }); } } // 启动认证服务 Future<void> _startAuth() async { // 替换为你的认证服务地址,redirect_uri设为自定义URL const authUrl = 'https://your-auth-service.com/authorize?redirect_uri=myapp://auth'; if (await canLaunchUrl(Uri.parse(authUrl))) { await launchUrl(Uri.parse(authUrl)); } else { throw '无法打开认证链接'; } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('认证参数获取示例')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton(onPressed: _startAuth, child: const Text('启动认证')), const SizedBox(height: 20), Text('Token: ${_token ?? '未获取'}'), Text('用户ID: ${_userId ?? '未获取'}'), ], ), ), ), ); } }
关键说明
- 自定义URL Scheme格式为
scheme://host,比如示例中的myapp://auth,需将认证服务的重定向地址设置为此值。 - 若需更高安全性(避免Scheme被其他App劫持),可使用iOS Universal Links或Android App Links,配置逻辑类似但需绑定域名证书,本质仍无需服务器。
内容的提问来源于stack exchange,提问作者Jigyasu Tanwar
相关产品推荐
相关产品推荐

