[React Native] Implement GoogleSignIn with Firebase in iOS

2022. 3. 18. 13:20React Native/API

Result


 

 

 

 

 

 

1. Create Firebase project in Firebase console

프로젝트 추가 버튼 눌러 프로젝트 생성
프로젝트 페이지에 들어가서 [+앱 추가] 버튼 클릭 - iOS 앱 추가


  • Apple bundle ID 입력 (Xocode - Show the project navigator - project - General - Identity - Bundle Identifier)




Add follow line in AppDelegate.m like this

@import UIKit;

@import Firebase;

FirebaseApp.configure()

⬇️

static void InitializeFlipper(UIApplication *application) {
  ...
}
#endif

@import UIKit;
@import Firebase;
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{
#ifdef FB_SONARKIT_ENABLED
  InitializeFlipper(application);
#endif

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  ...
  [FIRApp configure];
  return YES;
}

 

The app is now connected to Firebase.

 

 

 

 

 

2. Activate Google Login in Firebase

Firebase Dashboard-> Authentication -> Google Sign-in method -> 사용 설정 toggle


 

 

 

 

 

 

3. Install GoogleSignIn API / Firebase API

[ terminal ] in your project folder 

npm install -save @react-native-community/google-signin
npm install --save @react-native-firebase/app

cd ios
pod install
  • Set REVERTSED_CLIENT_ID in Xode > project > info > URL Types > + > URL Schemes

Copy REVERSED_CLIENT_ID
Paste here


 

 

 

 

 

 

4. Get ClientId, OAuth 동의 화면 설정

  • Get webClientId, iosClientId Google Cloud Platform > 사용자 인증 정보 > OAuth 2.0 클라이언트 ID

  • Configure in here (code)
GoogleSignin.configure({
	webClientId: '', // client ID of type WEB for your server (needed to verify user ID and offline access)
	iosClientId: '' // [iOS] optional, if you want
});
  • OAuth 동의 화면 설정
  • 테스트 사용자 > ADD USER에 테스트할 이메일 등록


 

 

 

 

 

 

 

5. Code

import React, { useState } from 'react';
import {
  Button,
  Image,
  SafeAreaView,
  StatusBar,
  StyleSheet,
  Text,
  View
} from 'react-native';
import {
  GoogleSignin,
  GoogleSigninButton,
  statusCodes
} from 'react-native-google-login';

const App = () => {
  const [pushData, setPushData] = useState();
  const [loggedIn, setLoggedIn] = useState(false);
  const [isSignInProgress, setIsSignInProgress] = useState(false);
  const [userInfo, setUserInfo] = useState();

  const signIn = async () => {
    try {
      await GoogleSignin.hasPlayServices();
      const userInfoFromGoogle = await GoogleSignin.signIn();
      console.log(userInfoFromGoogle);
      setUserInfo(userInfoFromGoogle);
      setLoggedIn(true);
    } catch (error) {
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        // user cancelled the login flow
      } else if (error.code === statusCodes.IN_PROGRESS) {
        // operation (f.e. sign in) is in progress already
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        // play services not available or outdated
      } else {
        // some other error happened
      }
    }
  };

  const signOut = async () => {
    try {
      await GoogleSignin.revokeAccess();
      await GoogleSignin.signOut();
      symbolicateStackTrace({ userInfo: null, loggedIn: false }); //Remember to remove the user from this app's state
    } catch (error) {
      console.error(error);
    }
  };
  
  React.useState(() => {
    GoogleSignin.configure({
      scopes: ['https://www.googleapis.com/auth/drive.readonly'], // what API you want to access on behalf of the user, default is email and profile
      webClientId:
        '559502922250-cvheetrgmhti559o4m7c6n2sla46ks5o.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
      offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
      hostedDomain: '', // specifies a hosted domain restriction
      loginHint: '', // [iOS] The user's ID, or email address, to be prefilled in the authentication UI if possible. [See docs here](https://developers.google.com/identity/sign-in/ios/api/interface_g_i_d_sign_in.html#a0a68c7504c31ab0b728432565f6e33fd)
      forceConsentPrompt: true, // [Android] if you want to show the authorization prompt at each login.
      accountName: '', // [Android] specifies an account name on the device that should be used
      iosClientId:
        '559502922250-rodebni93tivdt7015noe631upb22o1j.apps.googleusercontent.com' // [iOS] optional, if you want
    });
  });
  
  return (
    <SafeAreaView>
      <View>
        <StatusBar barStyle='dark-content' />
        <SafeAreaView>
          <View style={styles.sectionContainer}>
            <GoogleSigninButton
              style={{ width: 192, height: 48 }}
              size={GoogleSigninButton.Size.Wide}
              color={GoogleSigninButton.Color.Dark}
              onPress={signIn}
              disabled={isSignInProgress}
            />
          </View>
          <View style={styles.buttonContainer}>
            {!loggedIn && <Text>You are currently logged out</Text>}
            {loggedIn && (
              <Button
                onPress={signOut}
                title='Signout'
                color='#841584'
              ></Button>
            )}
          </View>
          {loggedIn && (
            <View>
              <View style={styles.listHeader}>
                <Text>User Info</Text>
              </View>
              <View style={styles.dp}>
                <Image
                  style={{ width: 100, height: 100 }}
                  source={{
                    uri: userInfo && userInfo.user && userInfo.user.photo
                  }}
                />
              </View>
              <View style={styles.detailContainer}>
                <Text style={styles.title}>Name</Text>
                <Text style={styles.message}>
                  {userInfo && userInfo.user && userInfo.user.name}
                </Text>
              </View>
              <View style={styles.detailContainer}>
                <Text style={styles.title}>Email</Text>
                <Text style={styles.message}>
                  {userInfo && userInfo.user && userInfo.user.email}
                </Text>
              </View>
              <View style={styles.detailContainer}>
                <Text style={styles.title}>ID</Text>
                <Text style={styles.message}>
                  {userInfo && userInfo.user && userInfo.user.id}
                </Text>
              </View>
            </View>
          )}
        </SafeAreaView>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  listHeader: {
    backgroundColor: '#eee',
    color: '#222',
    height: 44,
    padding: 12
  },
  detailContainer: {
    paddingHorizontal: 20
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    paddingTop: 10
  },
  message: {
    fontSize: 14,
    paddingBottom: 15,
    borderBottomColor: '#ccc',
    borderBottomWidth: 1
  },
  dp: {
    marginTop: 32,
    paddingHorizontal: 24,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  buttonContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
    flexDirection: 'row',
    justifyContent: 'center'
  }
});
export default App;

5. Result log

{ idToken: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  scopes: 
   [ 'https://www.googleapis.com/auth/userinfo.email',
     'https://www.googleapis.com/auth/userinfo.profile',
     'openid',
     'https://www.googleapis.com/auth/drive.readonly' ],
  user: 
   { photo: 'https://lh3.googleusercontent.com/a/XXXXXXX',
     givenName: 'X',
     familyName: 'XX',
     name: 'XXX',
     email: 'XXX@gmail.com',
     id: '100XXXXXXXXXXXXXXX' } }


더보기

Reference.
https://bangc.tistory.com/12

 

[React-Native] 리액트 네이티브(react-native) 구글 로그인 연동하기

앱에서 사용자들이 간편하게 로그인할 수 있는 sns 로그인 연동은 필수인 것 같습니다. 저도 안드로이드로는 구글 로그인 연동을 해봤었는데 이번에 프로젝트를 진행하면서 리액트 네이티브로

bangc.tistory.com

 

https://www.npmjs.com/package/react-native-google-login

 

react-native-google-login

Google Signin for your react native Android and IOS applications. Latest version: 1.2.5, last published: 3 years ago. Start using react-native-google-login in your project by running `npm i react-native-google-login`. There are no other projects in the npm

www.npmjs.com

​https://github.com/react-native-google-signin/google-signin

 

GitHub - react-native-google-signin/google-signin: Google Sign-in for your React Native applications

Google Sign-in for your React Native applications. Contribute to react-native-google-signin/google-signin development by creating an account on GitHub.

github.com

https://rnfirebase.io

 

React Native Firebase | React Native Firebase

Welcome to React Native Firebase! To get started, you must first setup a Firebase project and install the "app" module. React Native Firebase is the officially recommended collection of packages that brings React Native support for all Firebase services on

rnfirebase.io

https://github.com/react-native-google-signin/google-signin/issues/247

 

IOS login issue · Issue #247 · react-native-google-signin/google-signin

I am getting issue in login. I got bellow error message: Exception 'Your app is missing support for the following URL schemes: [google id] was thrown while invoking signIn on target RNGoogleSig...

github.com

https://diana-an.tistory.com/27

 

Google Calendar API - 1.2. GCP 설정: OAuth 인증 설정

1. 2020/09/10 - [Programmer/etc.] - Google Calendar API - 1.1. GCP 설정: 프로젝트 생성 및 API 사용 설정에 이어지는 글입니다. 2. Nodejs 웹서버에서 Google calendar API를 사용하는 방법이 기록된 글입니..

diana-an.tistory.com