Xamarin.Forms集成Google登录:如何配置Google API Authenticator的redirectUrl值?
你的400 invalid_request错误核心原因是RedirectUrl未在Google Cloud控制台正确注册,且当前代码使用的是教程示例URI,并非你应用的专属跳转地址。以下是完整的解决步骤:
一、正确配置RedirectUrl(必须在Google Cloud控制台注册)
1. Android平台
- RedirectUrl格式:
{你的应用包名}:/oauth2redirect
包名需与Android项目AndroidManifest.xml中的package值完全一致,例如你的包名是com.yourcompany.yourapp,则RedirectUrl为com.yourcompany.yourapp:/oauth2redirect - 同时在
AndroidManifest.xml中添加Intent过滤器,让系统拦截该跳转:
<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="com.yourcompany.yourapp" /> <!-- 替换为你的包名 --> </intent-filter>
2. iOS平台
- RedirectUrl格式:
{你的应用Bundle ID}:/oauth2redirect
Bundle ID需与iOS项目Info.plist中的CFBundleIdentifier完全一致 - 在
Info.plist中添加URL Scheme:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>com.yourcompany.yourapp</string> <!-- 替换为你的Bundle ID --> </array> </dict> </array>
3. Google Cloud控制台注册
进入你的Google Cloud项目 → API和服务 → 凭据 → 找到对应的OAuth 2.0客户端ID,在「已获授权的重定向URI」中添加对应平台的RedirectUrl(Android/iOS的地址分别添加)。
二、修正代码并实现登录后逻辑
替换示例RedirectUrl为你应用的专属地址,同时添加登录成功/失败的回调,实现用户信息获取和跳转主页面:
Xamarin.Auth.OAuth2Authenticator authenticator = null; private void SignInGoogleClicked(object sender, EventArgs e) { string redirectUri; switch (Xamarin.Forms.Device.RuntimePlatform) { case Device.Android: redirectUri = "com.yourcompany.yourapp:/oauth2redirect"; // 替换为你的Android包名 break; case Device.iOS: redirectUri = "com.yourcompany.yourapp:/oauth2redirect"; // 替换为你的iOS Bundle ID break; default: redirectUri = "com.yourcompany.yourapp:/oauth2redirect"; // Windows平台同理替换 break; } authenticator = new Xamarin.Auth.OAuth2Authenticator( clientId: "498923533154-uefrhbk3i9v7nqd7lep9lqb85u783m7v.apps.googleusercontent.com", scope: "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email", authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"), redirectUrl: new Uri(redirectUri), getUsernameAsync: null, isUsingNativeUI: false ) { AllowCancel = true, }; // 绑定登录回调 authenticator.Completed += OnAuthCompleted; authenticator.Error += OnAuthError; NavigateLoginPage(); } private async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e) { // 关闭登录页 if (login_page != null) { await Navigation.PopAsync(); } if (e.IsAuthenticated) { // 获取AccessToken var accessToken = e.Account.Properties["access_token"]; // 调用Google API获取用户信息 using (var client = new HttpClient()) { var response = await client.GetAsync($"https://www.googleapis.com/oauth2/v2/userinfo?access_token={accessToken}"); if (response.IsSuccessStatusCode) { var userJson = await response.Content.ReadAsStringAsync(); // 解析JSON获取用户姓名、邮箱等信息(需自己定义UserModel类) // var user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserModel>(userJson); } } // 跳转到主页面 Application.Current.MainPage = new NavigationPage(new HomePage()); } } private async void OnAuthError(object sender, AuthenticatorErrorEventArgs e) { // 关闭登录页并提示错误 if (login_page != null) { await Navigation.PopAsync(); } await DisplayAlert("登录失败", e.Message, "确定"); } Xamarin.Auth.XamarinForms.AuthenticatorPage login_page = null; private void NavigateLoginPage() { login_page = new Xamarin.Auth.XamarinForms.AuthenticatorPage() { Authenticator = authenticator, }; Navigation.PushAsync(login_page); }
三、关键注意事项
- 完全匹配原则:Google控制台注册的RedirectUrl和代码中的必须完全一致,大小写、拼写都不能出错
- 权限精简:如果不需要
cloud-healthcare权限,建议从scope中移除,减少权限申请流程和出错概率 - 版本兼容性:确保使用最新稳定版的Xamarin.Auth NuGet包
内容的提问来源于stack exchange,提问作者vytaute
相关产品推荐
相关产品推荐

