react-native-google-auth

repository·main·Indexed 41 days ago

https://github.com/sbaiahmed1/react-native-google-auth

A modern React Native Google Authentication library (v1.3.0) with TypeScript support. It integrates the latest Google Sign-In SDK, OAuth 2.0, and Android Credential Manager to provide Google Login and SSO across iOS and Android. The library includes an Expo Config Plugin for seamless integration and supports token management and One Tap Sign-In.

Tokens
23K
Snippets
64
Records
73
Agent score
95%

What's inside react-native-google-auth

  1. Google Sign-In Flow Types and Supported Platforms

    main

    The react-native-google-auth library supports several authentication patterns:

    • One Tap Sign-In: Seamless authentication using saved credentials.
    • Standard Sign-In: The traditional Google OAuth flow.
    • Silent Sign-In: Background authentication for returning users.
    • Server-Side Verification: Secure token validation on your backend.

    Platform Support:

    • iOS: Utilizes the Google Sign-In SDK with iOS Keychain storage.
    • Android: Utilizes the Credential Manager API with Android Keystore.
  2. Understand platform differences in Access Tokens

    main

    The availability of access tokens differs by platform due to the Android Credential Manager API:

    • iOS: Returns both idToken and accessToken.
    • Android: Returns idToken, but accessToken is always null.

    On Android, the Credential Manager API focuses on authentication (ID tokens). If your backend requires an access token, you must implement a separate OAuth2 flow or use the ID token for server-side token exchange.

  3. Implement One Tap Sign-In

    main

    One Tap Sign-In attempts to authenticate the user automatically using saved credentials. You should call GoogleAuth.signIn() on app startup and handle the response types:

    • success: User is authenticated.
    • noSavedCredentialFound: No credentials available; fallback to the standard sign-in flow.
    • cancelled: User dismissed the prompt.
    const handleOneTapSignIn = async () => {
      try {
        const response = await GoogleAuth.signIn();
        switch (response.type) {
          case 'success':
            setUser(response.data.user);
            break;
          case 'noSavedCredentialFound':
            // Fallback to standard sign-in
            break;
          case 'cancelled':
            break;
        }
      } catch (error) {
        console.error('One Tap Sign-In error:', error);
      }
    };
  4. Optimize Google Auth performance with lazy configuration

    main

    To avoid unnecessary initialization overhead, use a lazy configuration pattern. Ensure the library is configured only once before calling signIn().

    // Lazy configuration
    let isConfigured = false;
    
    const ensureConfigured = async () => {
      if (!isConfigured) {
        await GoogleAuth.configure(getProductionConfig());
        isConfigured = true;
      }
    };
    
    // Optimized sign-in
    const optimizedSignIn = async () => {
      await ensureConfigured();
      return await GoogleAuth.signIn();
    };
  5. Configure react-native-google-auth via Advanced Configuration

    main

    Use the advanced configuration pattern to provide custom client IDs or specify custom paths for your Google service files in app.config.js.

    export default {
      expo: {
        name: "Your App",
        plugins: [
          [
            "react-native-google-auth",
            {
              iosClientId: "your-ios-client-id.apps.googleusercontent.com",
              androidClientId: "your-android-client-id.apps.googleusercontent.com",
              googleServicesFile: "./path/to/google-services.json",
              iosGoogleServicesFile: "./path/to/GoogleService-Info.plist"
            }
          ]
        ]
      }
    };
  6. Configure Google Cloud Console for iOS

    main

    To use Google Authentication on iOS:

    1. Create an iOS OAuth 2.0 Client ID in the Google Cloud Console.
    2. Use your app's Bundle ID (e.g., com.yourcompany.yourapp) as the identifier.
    3. Download the generated plist file and save it as GoogleService-Info.plist.
    4. Place the file in your project root (for Expo) or ios/YourApp/ (for React Native CLI).
  7. Verify Google ID Tokens on your server

    main

    For security, never trust authentication state solely on the client side. Always send the idToken received from GoogleAuth to your backend server to verify its validity using Google's official verification methods.

    const verifyTokenOnServer = async (idToken: string) => {
      try {
        const response = await fetch('/api/auth/verify-google-token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ idToken })
        });
    
        if (!response.ok) {
          throw new Error('Token verification failed');
        }
    
        const result = await response.json();
        return result.valid;
      } catch (error) {
        console.error('Server verification failed:', error);
        return false;
      }
    };
  8. Build and run the iOS app

    main

    To run the application on an iOS Simulator or connected device, you must first install CocoaPods dependencies.

    1. Install CocoaPods via Ruby bundler (required on first clone or after updating native deps):
      bundle install
      bundle exec pod install
    2. Run the application:
      # Using npm
      npm run ios
      
      # OR using Yarn
      yarn ios
    # Using npm
    npm run ios
    
    # OR using Yarn
    yarn ios
  9. Implement Context-Based Authentication

    main

    For managing authentication state globally in a React application, wrap your app in an AuthProvider using React Context. This pattern allows you to initialize authentication, check for existing users, and handle token expiration automatically on app startup.

    Key methods to include in your context:

    • signIn(): Triggers the sign-in flow.
    • signOut(): Clears the user session.
    • refreshTokens(): Manually refreshes the current tokens.
    • getCurrentUser(): Retrieves the currently authenticated user.
    • isTokenExpired(): Checks if the current token is no longer valid.
    import React, { createContext, useContext, useEffect, useState } from 'react';
    import { GoogleAuth } from 'react-native-google-auth';
    
    const AuthContext = createContext(undefined);
    
    export const AuthProvider = ({ children }) => {
      const [user, setUser] = useState(null);
      const [isLoading, setIsLoading] = useState(true);
    
      useEffect(() => {
        const initializeAuth = async () => {
          try {
            await GoogleAuth.configure({
              iosClientId: 'YOUR_IOS_CLIENT_ID',
              androidClientId: 'YOUR_ANDROID_CLIENT_ID'
            });
    
            const currentUser = await GoogleAuth.getCurrentUser();
            if (currentUser) {
              const isExpired = await GoogleAuth.isTokenExpired();
              if (isExpired) {
                await GoogleAuth.refreshTokens();
              }
              setUser(currentUser);
            }
          } catch (error) {
            console.log('Auth initialization failed', error);
          } finally {
            setIsLoading(false);
          }
        };
    
        initializeAuth();
      }, []);
    
      // ... signIn, signOut, refreshTokens implementations
    
      return (
        <AuthContext.Provider value={{ user, isLoading, signIn, signOut, refreshTokens }}>
          {children}
        </AuthContext.Provider>
      );
    };
    
    export const useAuth = () => useContext(AuthContext);
  10. Setup Google Authentication in React Native CLI

    main

    iOS Setup

    1. Install pods: cd ios && pod install
    2. Configure Client ID:
      • Method A (Recommended): Add GIDClientID to ios/YourApp/Info.plist: <key>GIDClientID</key><string>YOUR_IOS_CLIENT_ID.apps.googleusercontent.com</string>
      • Method B: Pass it manually via GoogleAuth.configure({ iosClientId: '...' }).
    3. Add URL schemes: Add the following to ios/YourApp/Info.plist to handle the redirect:
      <key>CFBundleURLTypes</key>
      <array>
        <dict>
          <key>CFBundleURLName</key>
          <string>com.yourcompany.yourapp</string>
          <key>CFBundleURLSchemes</key>
          <array>
            <string>com.googleusercontent.apps.YOUR_IOS_CLIENT_ID</string>
          </array>
        </dict>
      </array>
    4. Handle URL in AppDelegate.swift: Import GoogleSignIn and add the application(_:open:options:) method to handle the URL.

    Android Setup

    1. Configure Client ID:
      • Method A (Recommended): Place google-services.json in the android/app/ directory. The library will automatically extract the Web client ID (client_type: 3) required for Credential Manager.
      • Method B: Provide the Web application client ID manually in GoogleAuth.configure({ androidClientId: '...' }).

    Crucial: For Android, always use the Web application OAuth client ID, not the Android OAuth client ID.

    import GoogleSignIn
    
    // Add this method to handle URL schemes in AppDelegate.swift
    func application(
      _ app: UIApplication,
      open url: URL,
      options: [UIApplication.OpenURLOptionsKey: Any] = [:]
    ) -> Bool {
      return GIDSignIn.sharedInstance.handle(url)
    }
  11. Reload the application

    main

    If you need to perform a full reload to reset the app state, use the following platform-specific shortcuts:

    • Android: Press the <kbd>R</kbd> key twice, or open the Dev Menu using <kbd>Ctrl</kbd> + <kbd>M</kbd> (Windows/Linux) or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> (macOS) and select "Reload".
    • iOS: Press <kbd>R</kbd> in the iOS Simulator.