Flutter中使用oauth2_client包的Google OAuth2重定向URL问题
解决Android Flutter应用通过Google OAuth2获取Token的重定向问题
1. Google Cloud控制台的关键配置
- 创建Web应用类型的OAuth客户端ID,添加格式为
https://你的验证过的域名/oauth2redirect的HTTPS重定向URI - 完成域名所有权验证:进入Google Cloud API控制台的「OAuth同意屏幕」→「域名验证」,添加目标域名(如
my.test.app),按提示完成验证(通常需上传验证文件到域名根目录) - 确保配置的redirect URI与代码中完全一致,包括路径部分
2. Android Manifest的正确配置
Android 12+要求导出的Activity必须显式设置android:exported="true",同时App Links需开启autoVerify="true",配置如下:
<activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity" android:exported="true"> <intent-filter android:label="flutter_web_auth_2" android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" android:host="my.test.app" android:pathPrefix="/oauth2redirect" /> </intent-filter> </activity>
host和pathPrefix需与redirect URI完全匹配autoVerify="true"会让系统验证域名所有权,确保仅你的应用能处理该链接
3. Flutter代码的参数对应
customUriScheme需设置为https以匹配HTTPS类型的redirect URI,代码调整如下:
GoogleOAuth2Client client = GoogleOAuth2Client( customUriScheme: 'https', // 对应HTTPS scheme redirectUri: 'https://my.test.app/oauth2redirect', // 与Google Cloud配置一致 ); var token = await client.getTokenWithAuthCodeFlow( clientId: '你的Web客户端ID', clientSecret: '你的Web客户端密钥', scopes: [ 'https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly' ], authCodeParams: {"prompt": "consent", "access_type": "offline"}, // 需offline参数获取refresh token );
access_type: "offline"是获取refresh token的必要条件- 使用Web应用类型的OAuth客户端ID和密钥,不要混用Android客户端的信息
4. 常见问题排查
- 「无法访问此网站」通常因域名未验证,Google拒绝重定向到未验证的HTTPS URI
- 跳转后未返回应用,检查Manifest是否设置
exported="true",以及域名验证是否完成 - Google Web客户端不允许非HTTPS的redirect URI,不要混用自定义scheme(如
com.example.calendar)
内容的提问来源于stack exchange,提问作者Paras Palli
相关产品推荐
相关产品推荐

