ReactNative) 파이어베이스 소셜로그인 (Google)

2022. 5. 14. 22:05프로그래밍/개인프로젝트

6. 소셜 로그인

 

6-1 구글 로그인

https://rnfirebase.io/auth/social-auth#google

 

Social Authentication | React Native Firebase

Copyright © 2017-2020 Invertase Limited. Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. Some partial documentation, under the

rnfirebase.io

더보기

Google

The google-signin library provides a wrapper around the official Google login library, allowing you to create a credential and sign-in to Firebase.

Most configuration is already setup when using Google Sign-In with Firebase, however you need to ensure your machines SHA1 key has been configured for use with Android. You can see how to generate the key on the Getting Started documentation.

Ensure the "Google" sign-in provider is enabled on the Firebase Console.

Follow these instructions to install and setup google-signin

Before triggering a sign-in request, you must initialize the Google SDK using your any required scopes and the webClientId, which can be found in the android/app/google-services.json file as the client/oauth_client/client_id property (the id ends with .apps.googleusercontent.com). Make sure to pick the client_id with client_type: 3

import { GoogleSignin } from '@react-native-google-signin/google-signin';

GoogleSignin.configure({
  webClientId: '',
});

Once initialized, setup your application to trigger a sign-in request with Google using the signIn method.

import React from 'react';
import { Button } from 'react-native';

function GoogleSignIn() {
  return (
    <Button
      title="Google Sign-In"
      onPress={() => onGoogleButtonPress().then(() => console.log('Signed in with Google!'))}
    />
  );
}

The onGoogleButtonPress can then be implemented as follows:

import auth from '@react-native-firebase/auth';
import { GoogleSignin } from '@react-native-google-signin/google-signin';

async function onGoogleButtonPress() {
  // Get the users ID token
  const { idToken } = await GoogleSignin.signIn();

  // Create a Google credential with the token
  const googleCredential = auth.GoogleAuthProvider.credential(idToken);

  // Sign-in the user with the credential
  return auth().signInWithCredential(googleCredential);
}

Firebase console에서 구글 로그인 활성화

(https://console.firebase.google.com/ -> 프로젝트 클릭 -> Authentication탭 클릭 -> Sign-in Method 클릭 - 새 제공업체 추가)

 

설치

npm install @react-native-google-signin/google-signin --save

App.js -> GoogleSignin라이브러리 import

// App.js
// ...code

import { GoogleSignin } from '@react-native-google-signin/google-signin';

// ...code

그 아래에 구글 로그인을 연동하기 위한 환경 세팅 작성

// App.js
// ...code

const googleSigninConfigure = () => { 
    GoogleSignin.configure({ webClientId: '웹클라이언트ID'}) 
}

// ...code

웹 클라이언트 ID??

Firebase console의 Authentication -> sign-in method -> 활성화시킨 구글 버튼 클릭 -> 웹 SDK구성 클릭하면 알 수 있다

 

useEffect로 위의 함수 호출

// App.js
// ...code

useEffect(()=>{
      googleSigninConfigure();
  },[])
  
// ...code

구글 로그인을 담당하는 커스텀 컴포넌트를 만든다

//GoogleLogin.js
import React from 'react';
import styled from "styled-components/native";
import {colors} from "../Color"
import {Ionicons} from "@expo/vector-icons";

import auth from '@react-native-firebase/auth';
import { GoogleSignin, GoogleSigninButton, statusCodes } from '@react-native-google-signin/google-signin';

const SocialSign = styled.TouchableOpacity`
    flex-direction: row;
    width: 70%;
    height: 45px;
    margin: 10px 0px;
    border-radius: 15px;
    align-items: center;
    justify-content: center;
`
const SocialText = styled.Text`
    color: white;
    font-size: 23px;
    font-family: "SDChild";
    font-size: 20px;
    padding: 0px 10px ;
`

const GoogleLogin = () => {

    //구글소셜로그인
    const onGoogleButtonPress = async () => { 
        const { idToken } = await GoogleSignin.signIn(); 
        const googleCredential = auth.GoogleAuthProvider.credential(idToken); 
        return auth().signInWithCredential(googleCredential); 
    }

    return (
    <>
    <SocialSign style={{backgroundColor:colors.BLUE}} onPress={() => onGoogleButtonPress()}>
        <Ionicons name="logo-google" size={22} color="white" /><SocialText>구글계정으로 시작하기</SocialText>
    </SocialSign>
    </>
    )
};
export default GoogleLogin;

로그인 화면에 GoogleLogin.js 파일 import 한 뒤 사용

// Login.js
// ...code

import GoogleLogin from "../component/firebaseComponent/GoogleLogin";

// ...code

<GoogleLogin />

// ...code

* 구글 로그인 API 사용 시 앱 크래쉬

Your app is missing support for the following URL schemes: com.googleusercontent.app