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

2022. 5. 19. 00:37프로그래밍/개인프로젝트

6. 소셜 로그인

6-2 애플 로그인

 

더보기

Apple

Starting April 2020, all existing applications using external 3rd party login services (such as Facebook, Twitter, Google etc) must ensure that Apple Sign-In is also provided. To learn more about these new guidelines, view the Apple announcement. Apple Sign-In is not required for Android devices.

To integrate Apple Sign-In on your iOS applications, you need to install a 3rd party library to authenticate with Apple. Once authentication is successful, a Firebase credential can be used to sign the user into Firebase with their Apple account.

To get started, you must first install the react-native-apple-authentication library. There are a number of prerequisites to using the library, including setting up your Apple Developer account to enable Apple Sign-In.

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

Once setup, we can trigger an initial request to allow the user to sign in with their Apple account, using a pre-rendered button the react-native-apple-authentication library provides:

import React from 'react';
import { AppleButton } from '@invertase/react-native-apple-authentication';

function AppleSignIn() {
  return (
    <AppleButton
      buttonStyle={AppleButton.Style.WHITE}
      buttonType={AppleButton.Type.SIGN_IN}
      style={{
        width: 160,
        height: 45,
      }}
      onPress={() => onAppleButtonPress().then(() => console.log('Apple sign-in complete!'))}
    />
  );
}

When the user presses the pre-rendered button, we can trigger the initial sign-in request using the performRequest method, passing in the scope required for our application:

import auth from '@react-native-firebase/auth';
import { appleAuth } from '@invertase/react-native-apple-authentication';

async function onAppleButtonPress() {
  // Start the sign-in request
  const appleAuthRequestResponse = await appleAuth.performRequest({
    requestedOperation: appleAuth.Operation.LOGIN,
    requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
  });

  // Ensure Apple returned a user identityToken
  if (!appleAuthRequestResponse.identityToken) {
    throw new Error('Apple Sign-In failed - no identify token returned');
  }

  // Create a Firebase credential from the response
  const { identityToken, nonce } = appleAuthRequestResponse;
  const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);

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

Upon successful sign-in, any onAuthStateChanged listeners will trigger with the new authentication state of the user.

 

1. Firebase console에서 애플 로그인 활성화

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

 

2. 애플 개발자 계정 생성

 

2-1. Apple Developer 접속 

 

Apple Developer

There’s never been a better time to develop for Apple platforms.

developer.apple.com

2-2. 우측 상단 Account 탭 클릭  ->  로그인

  - 개발 및 배포용으로 쓰던 계정으로 로그인했음

 

2-3. 하단 Join the Apple Developer Program 클릭

 

2-4. 우측 상단 Enroll 클릭

2-5. 가입정보 입력

(위아래 모두 영문으로 작성했음)

2-6. 개인 개발자 선택

2-7. 동의 후 결제 (129,000)

2-8. 결제 완료

구매 처리에 1~2일 소요됨

 

초기 개발 환경 설정

https://github.com/invertase/react-native-apple-authentication/blob/main/docs/INITIAL_SETUP.md

 

GitHub - invertase/react-native-apple-authentication: A React Native library providing support for Apple Authentication on iOS a

A React Native library providing support for Apple Authentication on iOS and Android. - GitHub - invertase/react-native-apple-authentication: A React Native library providing support for Apple Auth...

github.com

 

사진으로 잘 설명되어 있어서 따라 진행하기 편했음

 

설치하기 

npm install @invertase/react-native-apple-authentication

cd ios && pod install

 

문서

React Native Firebase를 통해 사용자 인증을 하기 때문에 Firebase guide를 읽고 개발했다

 

애플 로그인 컴포넌트 AppleLogin.js 생성

// AppleLogin.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 { appleAuth } from '@invertase/react-native-apple-authentication';

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 AppleLogin = () => {

    //애플소셜로그인
    async function onAppleButtonPress() {
        // 1). 로그인 요청 수행
        const appleAuthRequestResponse = await appleAuth.performRequest({
            requestedOperation: appleAuth.Operation.LOGIN,
            requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
        });
        // 2).요청이 성공하면 토큰과 nonce를 추출
        const { identityToken, nonce } = appleAuthRequestResponse;
        if (identityToken) {
            // 3).Firebase `AppleAuthProvider` credential 생성
            const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
        
            // 4). 생성된 `AppleAuthProvider` credential을 사용해서 Firebase인증 요청을 시작한다,
            //     이 예제에서는 `signInWithCredential`이 사용되지만, 기존 사용자와 연결하려면 `linkWithCredential`를 호출할 수 있다
            const userCredential = await auth().signInWithCredential(appleCredential);
        
            // 사용자가 로그인되면 모든Firebase의 `onAuthStateChanged` 리스너가 트리거된다 
            // console.log(`Login.js 애플을 통해 인증된 파이어베이스, 유저아이디: ${userCredential.user.uid}`);
          } else {
            // 재시도하기 위한 처리부분
          }
    }
    return (
    <>
        {appleAuth.isSupported && (
            <SocialSign style={{backgroundColor:colors.REALDARKGRAY}} onPress={() => onAppleButtonPress()}>
                <Ionicons name="logo-apple" size={22} color="white" /><SocialText>애플계정으로 시작하기</SocialText>
            </SocialSign>
        )}
    </>
    )
};
export default AppleLogin;

로그인하는 부분(Login.js)에서 애플 로그인 컴포넌트를 import 한 뒤 사용한다

// Login.js
// iOS에서만 버튼을 제공하기 위해 Platform import
import {Platform} from "react-native";
// AppleLogin 컴포넌트 import
import AppleLogin from "../component/firebaseComponent/AppleLogin";


// ...code

{Platform.OS == "ios" && (
    <AppleLogin />
)}