You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter移动端复用Web端Google(OAuth2)登录流程并获取令牌的方法问询

Google OAuth2 Login in Flutter: No Web Browser Required (Plus How to Get Your App Token)

Great question! Let’s break this down for your Flutter Android/iOS app—you don’t have to use a full system web browser for Google OAuth2 login, and there are two solid approaches to trigger the same auto-registration/token flow as your web app.

Do I need a web browser for the flow?

Nope. You have two primary options:

  1. Use the native Google Sign-In plugin (recommended for better user experience)
  2. Use a web view embedded in your app (if you need custom UI or specific OAuth behavior)

1. Native Google Sign-In Plugin (Best for Most Cases)

This approach leverages Android’s Google Play Services and iOS’s native Google Sign-In SDK, so users get the familiar system-level login prompt (no full browser needed). It’s faster, more secure, and feels native to the platform.

Steps to implement & get your app token:

  • Add the dependency: Add google_sign_in to your pubspec.yaml and run flutter pub get.
  • Configure OAuth credentials: In the Google Cloud Console, create separate OAuth client IDs for Android and iOS (match your app’s package name/bundle ID).
  • Code to sign in & retrieve tokens:
    import 'package:google_sign_in/google_sign_in.dart';
    
    final GoogleSignIn _googleSignIn = GoogleSignIn(
      scopes: [
        'email',
        'https://www.googleapis.com/auth/userinfo.profile',
      ],
    );
    
    Future<void> signInWithGoogle() async {
      try {
        // Trigger the native Google login flow
        final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
        if (googleUser == null) return; // User canceled login
    
        // Get authentication credentials from Google
        final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    
        // Extract tokens to send to your backend
        final String? idToken = googleAuth.idToken; // JWT token from Google
        final String? serverAuthCode = googleAuth.serverAuthCode; // For server-side token exchange
    
        // Send the idToken (or serverAuthCode) to your backend
        // Your backend will validate the token, create the user profile, and return YOUR app's login token
        // Example HTTP call (use http or dio package):
        // final response = await http.post(
        //   Uri.parse('https://your-backend.com/auth/google'),
        //   body: {'id_token': idToken},
        // );
        // if (response.statusCode == 200) {
        //   String appLoginToken = response.body;
        //   // Save this token locally (e.g., using shared_preferences) for future requests
        // }
      } catch (e) {
        print('Google Sign-In Error: $e');
      }
    }
    

Key Notes:

  • The idToken is a signed JWT that your backend can verify directly with Google’s public keys to confirm the user’s identity.
  • Once verified, your backend can create the user profile (auto-registration) and return your app’s custom login token just like it does for web users.

2. Embedded Web View Flow (For Custom UI/Edge Cases)

If you need full control over the login UI or have specific OAuth requirements, you can use an embedded web view to run the Google OAuth2 flow. This avoids opening the system browser but still uses the web-based auth flow.

Steps to implement & get your app token:

  • Add the dependency: Add webview_flutter to your pubspec.yaml.
  • Configure OAuth credentials: Create a Web OAuth client ID in Google Cloud Console, and set a custom redirect URI (e.g., yourapp://oauth-callback—make sure this URI is registered in the console).
  • Code to embed the web view & capture the auth code:
    import 'package:webview_flutter/webview_flutter.dart';
    import 'package:flutter/material.dart';
    
    class GoogleOAuthWebView extends StatefulWidget {
      const GoogleOAuthWebView({super.key});
    
      @override
      State<GoogleOAuthWebView> createState() => _GoogleOAuthWebViewState();
    }
    
    class _GoogleOAuthWebViewState extends State<GoogleOAuthWebView> {
      late WebViewController _webViewController;
      final String _authUrl = 'https://accounts.google.com/o/oauth2/v2/auth?'
          'client_id=YOUR_WEB_CLIENT_ID&'
          'redirect_uri=yourapp://oauth-callback&'
          'response_type=code&'
          'scope=email%20profile';
    
      @override
      void initState() {
        super.initState();
        _webViewController = WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onNavigationRequest: (NavigationRequest request) {
                // Listen for the custom redirect URI
                if (request.url.startsWith('yourapp://oauth-callback')) {
                  final Uri callbackUri = Uri.parse(request.url);
                  final String? authCode = callbackUri.queryParameters['code'];
    
                  if (authCode != null) {
                    // Send the auth code to your backend
                    // Your backend will exchange this code with Google for an idToken/accessToken,
                    // then create the user profile and return your app's login token
                    // _exchangeAuthCodeForAppToken(authCode);
                  }
    
                  // Close the web view
                  Navigator.pop(context);
                  return NavigationDecision.prevent;
                }
                return NavigationDecision.navigate;
              },
            ),
          )
          ..loadRequest(Uri.parse(_authUrl));
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('Sign in with Google')),
          body: WebViewWidget(controller: _webViewController),
        );
      }
    }
    

Key Notes:

  • Your backend will need to use the Web client ID and client secret to exchange the auth code for Google’s tokens.
  • After verifying the Google tokens, your backend proceeds with auto-registration and returns your app’s login token as usual.

Final Recommendation

Stick with the native Google Sign-In plugin whenever possible—it’s more seamless for users and requires less custom code. Only use the web view approach if you have specific needs that the native plugin can’t accommodate.

内容的提问来源于stack exchange,提问作者ankur_rajput

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:07:38