Cordova에서 OAuth 제공업체를 통해 인증

Firebase JS SDK를 사용하면 Firebase 사용자가 Cordova 환경에서 지원되는 모든 OAuth 제공업체를 통해 인증할 수 있습니다. 지원되는 OAuth 제공업체를 통합하려면 Firebase SDK를 사용하여 로그인 과정을 진행하거나, OAuth 과정을 수동으로 진행하면서 그 결과인 OAuth 인증 정보를 Firebase에 전달합니다.

Cordova용으로 Firebase 인증 설정

  1. 자바스크립트 프로젝트에 Firebase를 추가합니다. Firebase 스니펫을 추가할 때 my-app.firebaseapp.com 형식의 authDomain 구성 변수를 기록해 둡니다. Firebase에서 프로비저닝된 firebaseapp.com 도메인 대신 커스텀 도메인을 사용하는 경우 커스텀 도메인을 대신 사용해야 합니다.

  2. Android 앱을 설정하려면 Firebase Console에 Android 앱을 추가하고 앱 세부정보를 입력합니다. 생성된 google-services.json은 필요하지 않습니다.

  3. iOS 앱을 설정하려면 iOS 애플리케이션을 만들고 Firebase Console에 추가합니다. 이후에 커스텀 URL 스킴 플러그인을 설치할 때 iOS 번들 ID를 추가해야 합니다.

  4. Firebase 동적 링크 사용 설정:

    1. Firebase Console에서 동적 링크 섹션을 엽니다.
    2. 동적 링크 약관에 아직 동의하지 않았으며 동적 링크 도메인도 만들지 않았다면 지금 동의하고 만듭니다.

      동적 링크 도메인을 이미 만들었다면 기록해 둡니다. 동적 링크 도메인의 형식은 일반적으로 다음 예와 같습니다.

      example.page.link

      수신 링크를 가로채도록 Apple 또는 Android 앱을 구성할 때 이 값이 필요합니다.

  5. Firebase Console에서 Google 로그인을 사용 설정합니다.

    1. Firebase Console에서 인증 섹션을 엽니다.
    2. 로그인 방법 탭에서 Google 로그인 방법을 사용 설정하고 저장을 클릭합니다.
  6. Cordova 프로젝트에 필요한 플러그인을 설치합니다.

    # Plugin to pass application build info (app name, ID, etc) to the OAuth widget.
    cordova plugin add cordova-plugin-buildinfo --save
    # Plugin to handle Universal Links (Android app link redirects)
    cordova plugin add cordova-universal-links-plugin-fix --save
    # Plugin to handle opening secure browser views on iOS/Android mobile devices
    cordova plugin add cordova-plugin-browsertab --save
    # Plugin to handle opening a browser view in older versions of iOS and Android
    cordova plugin add cordova-plugin-inappbrowser --save
    # Plugin to handle deep linking through Custom Scheme for iOS
    # Substitute *com.firebase.cordova* with the iOS bundle ID of your app.
    cordova plugin add cordova-plugin-customurlscheme --variable \
        URL_SCHEME=com.firebase.cordova --save
    
  7. Cordova config.xml 파일에 다음 구성을 추가합니다. 여기서 AUTH_DOMAIN은 단계 (1)의 도메인이고, DYNAMIC_LINK_DOMAIN은 단계 (3c)의 도메인입니다.

    <universal-links>
        <host name="DYNAMIC_LINK_DOMAIN" scheme="https" />
        <host name="AUTH_DOMAIN" scheme="https">
            <path url="/__/auth/callback"/>
        </host>
    </universal-links>
    

    구성의 예시는 다음과 같습니다.

    <universal-links>
        <host name="example.page.link" scheme="https" />
        <host name="example-app.firebaseapp.com" scheme="https">
            <path url="/__/auth/callback"/>
        </host>
    </universal-links>
    

    커스텀 도메인 auth.custom.domain.com을 사용하는 경우 my-app.firebaseapp.com을 이 커스텀 도메인으로 대체합니다.

    Android 애플리케이션의 경우 launchModesingleTask를 사용해야 합니다.

    <preference name="AndroidLaunchMode" value="singleTask" />
    

Firebase SDK로 로그인 과정 처리

  1. Firebase 인증은 현재의 Cordova 환경을 올바르게 파악하기 위해 deviceReady 이벤트를 사용합니다. 이 이벤트가 트리거된 이후에 Firebase 앱 인스턴스가 초기화되는지 확인하세요.

  2. Google 제공업체 객체의 인스턴스를 생성합니다.

    웹 모듈식 API

    import { GoogleAuthProvider } from "firebase/auth/cordova";
    
    const provider = new GoogleAuthProvider();

    웹 네임스페이스화된 API

    var provider = new firebase.auth.GoogleAuthProvider();
  3. signInWithRedirect를 통해 Google 제공업체 객체를 사용해 Firebase에 인증합니다. signInWithPopup은 Cordova에서 지원되지 않습니다.

    웹 모듈식 API

    import { getAuth, signInWithRedirect, getRedirectResult, GoogleAuthProvider } from "firebase/auth/cordova";
    
    const auth = getAuth();
    signInWithRedirect(auth, new GoogleAuthProvider())
      .then(() => {
        return getRedirectResult(auth);
      })
      .then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
    
        // This gives you a Google Access Token.
        // You can use it to access the Google API.
        const token = credential.accessToken;
    
        // The signed-in user info.
        const user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
      });

    웹 네임스페이스화된 API

    firebase.auth().signInWithRedirect(provider).then(() => {
      return firebase.auth().getRedirectResult();
    }).then((result) => {
      /** @type {firebase.auth.OAuthCredential} */
      var credential = result.credential;
    
      // This gives you a Google Access Token.
      // You can use it to access the Google API.
      var token = credential.accessToken;
      // The signed-in user info.
      var user = result.user;
      // ...
    }).catch((error) => {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
    });
  4. 로그인 작업이 완료되기 전에 앱 활동이 소멸되는 경우를 처리하려면 앱이 로드될 때 getRedirectResult를 호출합니다.

    웹 모듈식 API

    import { getAuth, getRedirectResult, GoogleAuthProvider } from "firebase/auth/cordova";
    
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        if (credential) {        
          // This gives you a Google Access Token.
          // You can use it to access the Google API.
          const token = credential.accessToken;
          // The signed-in user info.
          const user = result.user;
          // ...
        }
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
      });

    웹 네임스페이스화된 API

    firebase.auth().getRedirectResult().then((result) => {
      if (result.credential) {
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // This gives you a Google Access Token.
        // You can use it to access the Google API.
        var token = credential.accessToken;
        // The signed-in user info.
        var user = result.user;
        // ...
      }
    }).catch((error) => {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
    });

    동일한 메커니즘을 사용하여 linkWithRedirect를 통해 새 제공업체를 연결하거나 reauthenticateWithRedirect를 통해 기존 제공업체로 다시 인증할 수 있습니다.