자바스크립트에서 Facebook 로그인을 사용하여 인증

Facebook 로그인을 앱에 통합하여 사용자가 Facebook 계정으로 Firebase에 인증하도록 할 수 있습니다. Facebook 로그인을 통합하려면 Firebase SDK를 사용해 로그인 과정을 진행해도 되고, Facebook 로그인 과정을 수동으로 진행하고 그 결과인 액세스 토큰을 Firebase에 전달해도 됩니다.

시작하기 전에

  1. 자바스크립트 프로젝트에 Firebase를 추가합니다.
  2. Facebook for Developers 사이트에서 내 앱의 앱 ID앱 비밀번호를 가져옵니다.
  3. 다음과 같이 Facebook 로그인을 사용 설정합니다.
    1. Firebase Console에서 인증 섹션을 엽니다.
    2. 로그인 방법 탭에서 Facebook 로그인 방법을 사용 설정하고 Facebook에서 받은 앱 ID앱 비밀번호를 지정합니다.
    3. Facebook for Developers 사이트의 Facebook 앱 설정 페이지에서 제품 설정 > Facebook 로그인 구성에 개발자의 OAuth 리디렉션 URI(예: my-app-12345.firebaseapp.com/__/auth/handler)가 OAuth 리디렉션 URI 중 하나로 표시되어 있는지 확인합니다.

Firebase SDK로 로그인 과정 처리

웹 앱을 개발하는 경우 Facebook 계정을 통해 Firebase에 사용자를 인증하는 가장 쉬운 방법은 Firebase 자바스크립트 SDK로 로그인 과정을 처리하는 것입니다. Node.js 또는 브라우저가 아닌 환경에서 사용자를 인증하려면 로그인 과정을 직접 처리해야 합니다.

Firebase 자바스크립트 SDK로 로그인 과정을 처리하려면 다음 단계를 따르세요.

  1. 다음과 같이 Facebook 제공업체 객체의 인스턴스를 생성합니다.

    웹 모듈식 API

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

    웹 네임스페이스화된 API

    var provider = new firebase.auth.FacebookAuthProvider();
  2. 선택사항: 인증 제공업체에 요청하고자 하는 OAuth 2.0 범위를 추가로 지정합니다. 범위를 추가하려면 addScope를 호출합니다. 예를 들면 다음과 같습니다.

    웹 모듈식 API

    provider.addScope('user_birthday');

    웹 네임스페이스화된 API

    provider.addScope('user_birthday');
    인증 제공업체 문서를 참조하세요.
  3. 선택사항: 관련 커스텀 OAuth 매개변수를 명시적으로 전달하지 않고 제공업체의 OAuth 과정을 사용자가 선호하는 언어로 현지화하려면 OAuth 과정을 시작하기 전에 인증 인스턴스의 언어 코드를 업데이트합니다. 예를 들면 다음과 같습니다.

    웹 모듈식 API

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // auth.useDeviceLanguage();

    웹 네임스페이스화된 API

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  4. 선택사항: OAuth 요청과 함께 전송할 커스텀 OAuth 제공업체 매개변수를 추가로 지정합니다. 커스텀 매개변수를 추가하려면 OAuth 제공업체 문서에 지정된 키가 포함된 객체와 해당 값을 사용하여 초기화된 제공업체에서 setCustomParameters를 호출합니다. 예를 들면 다음과 같습니다.

    웹 모듈식 API

    provider.setCustomParameters({
      'display': 'popup'
    });

    웹 네임스페이스화된 API

    provider.setCustomParameters({
      'display': 'popup'
    });
    예약된 필수 OAuth 매개변수는 허용되지 않으며 무시됩니다. 자세한 내용은 인증 제공업체 참조를 확인하세요.
  5. Facebook 제공업체 객체를 사용해 Firebase 인증을 진행합니다. 팝업 창을 띄우거나 로그인 페이지로 리디렉션하여 사용자가 Facebook 계정에 로그인하도록 유도할 수 있습니다. 휴대기기의 경우 리디렉션을 사용할 것을 권장합니다.
    • 팝업 창을 사용하여 로그인 과정을 진행하려면 signInWithPopup을 호출합니다.

      웹 모듈식 API

      import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // The signed-in user info.
          const user = result.user;
      
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          const credential = FacebookAuthProvider.credentialFromResult(result);
          const accessToken = credential.accessToken;
      
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        })
        .catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // The AuthCredential type that was used.
          const credential = FacebookAuthProvider.credentialFromError(error);
      
          // ...
        });

      웹 네임스페이스화된 API

      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
      
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
      
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          var accessToken = credential.accessToken;
      
          // ...
        })
        .catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
      
          // ...
        });
      또한 Facebook 제공업체의 OAuth 토큰을 받아서 Facebook API를 통해 추가 데이터를 가져올 수도 있습니다.

      이 시점에 오류를 파악해서 처리할 수도 있습니다. 오류 코드 목록은 인증 참고 문서에서 확인할 수 있습니다.

    • 로그인 페이지로 리디렉션해서 로그인 과정을 진행하려면 signInWithRedirect를 호출합니다. `signInWithRedirect`를 사용할 때는 권장사항을 따르세요.

      웹 모듈식 API

      import { getAuth, signInWithRedirect } from "firebase/auth";
      
      const auth = getAuth();
      signInWithRedirect(auth, provider);

      웹 네임스페이스화된 API

      firebase.auth().signInWithRedirect(provider);
      페이지 로드가 완료되면 getRedirectResult를 호출해서 Facebook 제공업체의 OAuth 토큰을 가져올 수도 있습니다.

      웹 모듈식 API

      import { getAuth, getRedirectResult, FacebookAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      getRedirectResult(auth)
        .then((result) => {
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          const credential = FacebookAuthProvider.credentialFromResult(result);
          const token = credential.accessToken;
      
          const user = result.user;
          // IdP data available using getAdditionalUserInfo(result)
          // ...
        }).catch((error) => {
          // Handle Errors here.
          const errorCode = error.code;
          const errorMessage = error.message;
          // The email of the user's account used.
          const email = error.customData.email;
          // AuthCredential type that was used.
          const credential = FacebookAuthProvider.credentialFromError(error);
          // ...
        });

      웹 네임스페이스화된 API

      firebase.auth()
        .getRedirectResult()
        .then((result) => {
          if (result.credential) {
            /** @type {firebase.auth.OAuthCredential} */
            var credential = result.credential;
      
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = credential.accessToken;
            // ...
          }
          // The signed-in user info.
          var user = result.user;
          // IdP data available in result.additionalUserInfo.profile.
            // ...
        }).catch((error) => {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      이 단계에서 오류를 파악해서 처리할 수도 있습니다. 오류 코드 목록은 인증 참고 문서에서 확인할 수 있습니다.

Chrome 확장 프로그램에서 Firebase에 인증

Chrome 확장 프로그램 앱을 빌드하는 경우 Chrome 확장 프로그램 ID를 추가해야 합니다.

  1. Firebase Console에서 프로젝트를 엽니다.
  2. 인증 섹션에서 로그인 방법 페이지를 엽니다.
  3. 승인된 도메인 목록에 다음과 같은 URI를 추가합니다.
    chrome-extension://CHROME_EXTENSION_ID

Chrome 확장 프로그램에서는 HTTP 리디렉션을 사용할 수 없으므로 팝업 작업(signInWithPopup, linkWithPopup, reauthenticateWithPopup)만 사용할 수 있습니다. 인증 팝업이 브라우저 작업 팝업을 취소하므로 브라우저 작업 팝업이 아닌 백그라운드 페이지 스크립트에서 이러한 메서드를 호출해야 합니다. 팝업 메서드는 매니페스트 V2를 사용하는 확장 프로그램에서만 사용할 수 있습니다. 최신 매니페스트 V3은 팝업 작업을 전혀 수행할 수 없는 서비스 워커 형식의 백그라운드 스크립트만 허용합니다.

Chrome 확장 프로그램의 매니페스트 파일에서 https://apis.google.com URL이 content_security_policy 허용 목록에 추가되었는지 확인합니다.

다음 단계

사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트에 저장되며 사용자의 로그인 방법과 무관하게 프로젝트 내의 모든 앱에서 사용자 본인 확인에 사용할 수 있습니다.

  • 앱에서 사용자의 인증 상태를 파악할 때 권장하는 방법은 Auth 객체에 관찰자를 설정하는 것입니다. 그러면 User 객체로부터 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요.

  • Firebase 실시간 데이터베이스와 Cloud Storage 보안 규칙auth 변수에서 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 통해 사용자가 액세스할 수 있는 데이터를 관리할 수 있습니다.

인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.

사용자를 로그아웃시키려면 signOut을 호출합니다.

웹 모듈식 API

import { getAuth, signOut } from "firebase/auth";

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});

웹 네임스페이스화된 API

firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});