Facebook 로그인을 앱에 통합하여 사용자가 Facebook 계정으로 Firebase에 인증하도록 할 수 있습니다. Facebook 로그인을 통합하려면 Firebase SDK를 사용해 로그인 과정을 진행해도 되고, Facebook 로그인 과정을 수동으로 진행하고 그 결과인 액세스 토큰을 Firebase에 전달해도 됩니다.
시작하기 전에
- 자바스크립트 프로젝트에 Firebase를 추가합니다.
- Facebook for Developers 사이트에서 내 앱의 앱 ID와 앱 비밀번호를 가져옵니다.
- 다음과 같이 Facebook 로그인을 사용 설정합니다.
- Firebase Console에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 Facebook 로그인 방법을 사용 설정하고 Facebook에서 받은 앱 ID와 앱 비밀번호를 지정합니다.
- 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로 로그인 과정을 처리하려면 다음 단계를 따르세요.
- 다음과 같이 Facebook 제공업체 객체의 인스턴스를 생성합니다.
import { FacebookAuthProvider } from "firebase/auth"; const provider = new FacebookAuthProvider();
var provider = new firebase.auth.FacebookAuthProvider();
- 선택사항: 인증 제공업체에 요청하고자 하는 OAuth 2.0 범위를 추가로 지정합니다. 범위를 추가하려면
addScope
를 호출합니다. 예를 들면 다음과 같습니다.provider.addScope('user_birthday');
provider.addScope('user_birthday');
- 선택사항: 관련 커스텀 OAuth 매개변수를 명시적으로 전달하지 않고 제공업체의 OAuth 과정을 사용자가 선호하는 언어로 현지화하려면 OAuth 과정을 시작하기 전에 인증 인스턴스의 언어 코드를 업데이트합니다. 예를 들면 다음과 같습니다.
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
- 선택사항: OAuth 요청과 함께 전송할 커스텀 OAuth 제공업체 매개변수를 추가로 지정합니다. 커스텀 매개변수를 추가하려면 OAuth 제공업체 문서에 지정된 키가 포함된 객체와 해당 값을 사용하여 초기화된 제공업체에서
setCustomParameters
를 호출합니다. 예를 들면 다음과 같습니다.provider.setCustomParameters({ 'display': 'popup' });
provider.setCustomParameters({ 'display': 'popup' });
- Facebook 제공업체 객체를 사용해 Firebase 인증을 진행합니다. 팝업 창을
띄우거나 로그인 페이지로 리디렉션하여 사용자가 Facebook 계정에
로그인하도록 유도할 수 있습니다. 휴대기기의 경우 리디렉션을 사용할 것을 권장합니다.
- 팝업 창을 사용하여 로그인하려면
signInWithPopup
을 호출합니다.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); // ... });
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; // ... });
이 시점에 오류를 파악해서 처리할 수도 있습니다. 오류 코드 목록은 인증 참고 문서에서 확인할 수 있습니다.
- 로그인 페이지로 리디렉션해서 로그인 과정을 진행하려면
signInWithRedirect
를 호출합니다. `signInWithRedirect`를 사용할 때는 권장사항을 따르세요.import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
firebase.auth().signInWithRedirect(provider);
getRedirectResult
를 호출해서 Facebook 제공업체의 OAuth 토큰을 가져올 수도 있습니다.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); // ... });
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; // ... });
- 팝업 창을 사용하여 로그인하려면
account-exists-with-different-credential 오류 처리
Firebase 콘솔에서 이메일 주소당 계정 1개를 사용 설정한 경우 다른 Firebase 사용자의 제공업체(예: Google)에 이미 존재하는 이메일을 사용하여 Facebook과 같은 제공업체에 로그인을 시도하면 AuthCredential
객체(Facebook 액세스 토큰)와 함께 auth/account-exists-with-different-credential
오류가 발생합니다. 사용자가 원하는 제공업체에 로그인하려면 먼저 기존 제공업체(Google)에 로그인한 다음 신규 제공업체의 AuthCredential
(Facebook 액세스 토큰)에 연결해야 합니다.
팝업 모드
signInWithPopup
을 사용하는 경우 다음 예시와 같은 코드를 사용해 auth/account-exists-with-different-credential
오류를 처리할 수 있습니다.
import { getAuth, linkWithCredential, signInWithPopup, FacebookAuthProvider, } from "firebase/auth"; try { // Step 1: User tries to sign in using Facebook. let result = await signInWithPopup(getAuth(), new FacebookAuthProvider()); } catch (error) { // Step 2: User's email already exists. if (error.code === "auth/account-exists-with-different-credential") { // The pending Facebook credential. let pendingCred = error.credential; // Step 3: Save the pending credential in temporary storage, // Step 4: Let the user know that they already have an account // but with a different provider, and let them choose another // sign-in method. } } // ... try { // Step 5: Sign the user in using their chosen method. let result = await signInWithPopup(getAuth(), userSelectedProvider); // Step 6: Link to the Facebook credential. // TODO: implement `retrievePendingCred` for your app. let pendingCred = retrievePendingCred(); if (pendingCred !== null) { // As you have access to the pending credential, you can directly call the // link method. let user = await linkWithCredential(result.user, pendingCred); } // Step 7: Continue to app. } catch (error) { // ... }
리디렉션 모드
리디렉션 모드에서도 오류를 비슷한 방식으로 처리하지만, 페이지 리디렉션 사이에 대기 중인 사용자 인증 정보를 캐시해야 한다는 점이 다릅니다(예: 세션 스토리지 사용).
고급: 수동으로 로그인 과정 처리
Facebook 계정을 사용해 Firebase에 인증할 때는 Facebook 로그인 자바스크립트 SDK로 로그인 과정을 처리하는 방법도 있습니다.
- 개발자 문서를 참고해 앱에서 Facebook 로그인을
사용할 수 있게 설정합니다.
다음과 같이 Facebook 앱 ID를 입력하여 Facebook 로그인을 구성합니다.
<script src="//connect.facebook.net/en_US/sdk.js"></script> <script> FB.init({ /********************************************************************** * TODO(Developer): Change the value below with your Facebook app ID. * **********************************************************************/ appId: '<YOUR_FACEBOOK_APP_ID>', status: true, xfbml: true, version: 'v2.6', }); </script>
-
또한 다음과 같이 Facebook 인증 상태에 리스너를 설정합니다.
FB.Event.subscribe('auth.authResponseChange', checkLoginState);
- Facebook 로그인을 통합한 다음에는 다음과 같이 웹 페이지에 Facebook 로그인 버튼을 추가합니다.
<fb:login-button data-auto-logout-link="true" scope="public_profile,email" size="large" ></fb:login-button>
- Facebook 인증 상태 콜백에서 Facebook의 인증 응답의 인증 토큰을 Firebase 사용자 인증 정보로 교환하여 Firebase에 로그인합니다.
import { getAuth, onAuthStateChanged, signInWithCredential, signOut, FacebookAuthProvider } from "firebase/auth"; const auth = getAuth(); function checkLoginState(response) { if (response.authResponse) { // User is signed-in Facebook. const unsubscribe = onAuthStateChanged(auth, (firebaseUser) => { unsubscribe(); // Check if we are already signed-in Firebase with the correct user. if (!isUserEqual(response.authResponse, firebaseUser)) { // Build Firebase credential with the Facebook auth token. const credential = FacebookAuthProvider.credential( response.authResponse.accessToken); // Sign in with the credential from the Facebook user. signInWithCredential(auth, credential) .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); // ... }); } else { // User is already signed-in Firebase with the correct user. } }); } else { // User is signed-out of Facebook. signOut(auth); } }
function checkLoginState(response) { if (response.authResponse) { // User is signed-in Facebook. var unsubscribe = firebase.auth().onAuthStateChanged((firebaseUser) => { unsubscribe(); // Check if we are already signed-in Firebase with the correct user. if (!isUserEqual(response.authResponse, firebaseUser)) { // Build Firebase credential with the Facebook auth token. var credential = firebase.auth.FacebookAuthProvider.credential( response.authResponse.accessToken); // Sign in with the credential from the Facebook user. firebase.auth().signInWithCredential(credential) .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; // ... }); } else { // User is already signed-in Firebase with the correct user. } }); } else { // User is signed-out of Facebook. firebase.auth().signOut(); } }
- 또한 불필요한 재인증을 피하려면 해당 Facebook 사용자가 이미 Firebase에 로그인하지 않았는지 확인해야 합니다.
import { FacebookAuthProvider } from "firebase/auth"; function isUserEqual(facebookAuthResponse, firebaseUser) { if (firebaseUser) { const providerData = firebaseUser.providerData; for (let i = 0; i < providerData.length; i++) { if (providerData[i].providerId === FacebookAuthProvider.PROVIDER_ID && providerData[i].uid === facebookAuthResponse.userID) { // We don't need to re-auth the Firebase connection. return true; } } } return false; }
function isUserEqual(facebookAuthResponse, firebaseUser) { if (firebaseUser) { var providerData = firebaseUser.providerData; for (var i = 0; i < providerData.length; i++) { if (providerData[i].providerId === firebase.auth.FacebookAuthProvider.PROVIDER_ID && providerData[i].uid === facebookAuthResponse.userID) { // We don't need to re-auth the Firebase connection. return true; } } } return false; }
고급: Node.js에서 Firebase에 인증
Node.js 애플리케이션에서 Firebase에 인증하는 방법은 다음과 같습니다.
- Facebook 계정으로 사용자를 로그인하고 사용자의 Facebook 액세스 토큰을 가져옵니다. 예를 들어 로그인 흐름 수동으로 처리하기 섹션의 설명에 따라 브라우저에서 사용자를 로그인한 후 액세스 토큰을 클라이언트 앱에서 사용하는 대신 Node.js 애플리케이션으로 전송합니다.
- 사용자의 Facebook 액세스 토큰을 가져왔으면 이 토큰으로 사용자 인증 정보 객체를 만들고 이 객체로 사용자를 로그인시킵니다.
import { getAuth, signInWithCredential, FacebookAuthProvider } from "firebase/auth"; // Sign in with the credential from the Facebook user. const auth = getAuth(); signInWithCredential(auth, credential) .then((result) => { // Signed in const credential = FacebookAuthProvider.credentialFromResult(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); // ... });
// Sign in with the credential from the Facebook user. firebase.auth().signInWithCredential(credential) .then((result) => { // Signed in var credential = result.credential; // ... }) .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 확장 프로그램 앱을 빌드하는 경우에는 오프스크린 문서 가이드를 참조하세요.
Facebook 로그인을 위한 리디렉션 도메인 맞춤설정
프로젝트를 만들 때 Firebase에서는 프로젝트의 고유한 하위 도메인(https://my-app-12345.firebaseapp.com
)을 프로비저닝합니다.
이 도메인은 OAuth 로그인을 위한 리디렉션 메커니즘으로도 사용됩니다. 이 도메인은 지원되는 모든 OAuth 제공업체에 대해 허용되어야 합니다. 하지만 이로 인해 사용자는 애플리케이션으로 다시 리디렉션되기 전에 Facebook에 로그인하는 과정에서 이 도메인을 볼 수 있습니다. 다음으로 이동: https://my-app-12345.firebaseapp.com
하위 도메인이 표시되지 않게 하려면 Firebase Hosting으로 커스텀 도메인을 설정하면 됩니다.
- Hosting용 도메인 설정의 1~3단계를 따릅니다. 도메인 소유권을 확인하면 Hosting에서 커스텀 도메인의 SSL 인증서를 프로비저닝합니다.
- Firebase Console에서 승인된 도메인 목록에 커스텀 도메인
auth.custom.domain.com
을 추가합니다. - Facebook 개발자 콘솔 또는 OAuth 설정 페이지에서 커스텀 도메인
https://auth.custom.domain.com/__/auth/handler
에서 액세스할 수 있는 리디렉션 페이지의 URL을 허용 목록에 추가합니다. - 자바스크립트 라이브러리를 초기화할 때는
authDomain
필드를 사용하여 커스텀 도메인을 지정합니다.var config = { apiKey: '...', // Changed from '
PROJECT_ID .firebaseapp.com'. authDomain: 'auth.custom.domain.com', databaseURL: 'https://PROJECT_ID .firebaseio.com', projectId: 'PROJECT_ID ', storageBucket: ' ', messagingSenderId: 'PROJECT_ID .firebasestorage.appSENDER_ID ' }; firebase.initializeApp(config);
다음 단계
사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트에 저장되며 사용자의 로그인 방법과 무관하게 프로젝트 내의 모든 앱에서 사용자 본인 확인에 사용할 수 있습니다.
-
앱에서 사용자의 인증 상태를 파악할 때 권장하는 방법은
Auth
객체에 관찰자를 설정하는 것입니다. 그러면User
객체로부터 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요. Firebase Realtime Database와 Cloud Storage 보안 규칙의
auth
변수에서 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 통해 사용자가 액세스할 수 있는 데이터를 관리할 수 있습니다.
인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.
사용자를 로그아웃시키려면 signOut
을 호출합니다.
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
firebase.auth().signOut().then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });