사용자가 Google 계정을 사용하여 Firebase에 인증하도록 설정할 수 있습니다. Firebase SDK를 사용하여 Google 로그인 과정을 진행하거나, Google 계정으로 로그인 라이브러리를 사용하고 그에 따른 ID 토큰을 Firebase에 전달하여 수동으로 로그인 과정을 진행할 수 있습니다.
시작하기 전에
- 자바스크립트 프로젝트에 Firebase를 추가합니다.
- Firebase Console에서 Google을 로그인 방법으로 사용 설정합니다.
- Firebase Console에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 Google 로그인 방법을 사용 설정하고 저장을 클릭합니다.
Firebase SDK로 로그인 과정 처리
웹 앱을 빌드하는 경우, Google 계정을 통해 Firebase에 사용자를 인증하는 가장 쉬운 방법은 Firebase 자바스크립트 SDK로 로그인 과정을 처리하는 것입니다. Node.js 또는 브라우저가 아닌 환경에서 사용자를 인증하려면 로그인 과정을 직접 처리해야 합니다.
Firebase 자바스크립트 SDK로 로그인 과정을 처리하려면 다음 단계를 따르세요.
- Google 제공업체 객체의 인스턴스를 생성합니다.
import { GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider();
var provider = new firebase.auth.GoogleAuthProvider();
- 선택사항: 인증 제공업체에 요청하고자 하는 OAuth 2.0 범위를 추가로 지정합니다. 범위를 추가하려면
addScope
를 호출합니다. 예를 들면 다음과 같습니다.provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
- 선택사항: 관련 커스텀 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({ 'login_hint': 'user@example.com' });
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
- Google 제공업체 객체를 사용해 Firebase에 인증합니다. 팝업 창을 띄우거나 로그인 페이지로 리디렉션하여 사용자가 Google 계정에 로그인하도록 유도할 수 있습니다. 휴대기기의 경우 리디렉션을 사용할 것을 권장합니다.
- 팝업 창을 사용하여 로그인하려면
signInWithPopup
을 호출합니다.import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; const auth = getAuth(); signInWithPopup(auth, provider) .then((result) => { // This gives you a Google Access Token. You can use it to access the Google API. const credential = GoogleAuthProvider.credentialFromResult(result); const token = credential.accessToken; // The signed-in user info. 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; // The AuthCredential type that was used. const credential = GoogleAuthProvider.credentialFromError(error); // ... });
firebase.auth() .signInWithPopup(provider) .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; // 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; // ... });
이 시점에 오류를 파악해서 처리할 수도 있습니다. 오류 코드 목록은 인증 참고 문서에서 확인할 수 있습니다.
- 로그인 페이지로 리디렉션해서 로그인 과정을 진행하려면
signInWithRedirect
를 호출합니다. `signInWithRedirect`를 사용할 때는 권장사항을 따르세요.import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
firebase.auth().signInWithRedirect(provider);
getRedirectResult
를 호출하여 Google 제공업체의 OAuth 토큰을 검색할 수 있습니다.import { getAuth, getRedirectResult, GoogleAuthProvider } from "firebase/auth"; const auth = getAuth(); getRedirectResult(auth) .then((result) => { // This gives you a Google Access Token. You can use it to access Google APIs. const credential = GoogleAuthProvider.credentialFromResult(result); const token = credential.accessToken; // The signed-in user info. 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; // The AuthCredential type that was used. const credential = GoogleAuthProvider.credentialFromError(error); // ... });
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; // 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 사용자의 제공업체(예: Facebook)에 이미 존재하는 이메일을 사용하여 Google과 같은 제공업체에 로그인을 시도하면 AuthCredential
객체(Google ID 토큰)와 함께 auth/account-exists-with-different-credential
오류가 발생합니다. 원하는 제공업체에 로그인하려면 사용자는 먼저 기존 제공업체(예: Facebook)에 로그인한 다음 다른 제공업체의 AuthCredential
(Google ID 토큰)에 연결해야 합니다.
팝업 모드
signInWithPopup
을 사용하는 경우 다음 예시와 같은 코드를 사용해 auth/account-exists-with-different-credential
오류를 처리할 수 있습니다.
import { getAuth, linkWithCredential, signInWithPopup, GoogleAuthProvider, } from "firebase/auth"; try { // Step 1: User tries to sign in using Google. let result = await signInWithPopup(getAuth(), new GoogleAuthProvider()); } catch (error) { // Step 2: User's email already exists. if (error.code === "auth/account-exists-with-different-credential") { // The pending Google 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 Google 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) { // ... }
리디렉션 모드
리디렉션 모드에서도 오류를 비슷한 방식으로 처리하지만, 페이지 리디렉션 사이에 대기 중인 사용자 인증 정보를 캐시해야 한다는 점이 다릅니다(예: 세션 스토리지 사용).
고급: 수동으로 로그인 과정 처리
'Google 계정으로 로그인' 라이브러리로 로그인 과정을 처리하여 Google 계정을 사용해 Firebase에 인증할 수도 있습니다.
- 통합 가이드에 따라 앱에 Google 계정으로 로그인을 통합합니다. 이때 Firebase 프로젝트용으로 생성된 Google 클라이언트 ID로 Google 로그인을 구성해야 합니다. 프로젝트의 Google 클라이언트 ID는 프로젝트 Developers Console의 사용자 인증 정보 페이지에서 확인할 수 있습니다.
- 로그인 결과 콜백에서 Google 인증 응답의 ID 토큰을 Firebase 사용자 인증 정보로 교환하여 Firebase에 인증하는 데 사용합니다.
function handleCredentialResponse(response) { // Build Firebase credential with the Google ID token. const idToken = response.credential; const credential = GoogleAuthProvider.credential(idToken); // Sign in with credential from the Google 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.email; // The credential that was used. const credential = GoogleAuthProvider.credentialFromError(error); // ... }); }
고급: Node.js에서 Firebase에 인증
Node.js 애플리케이션에서 Firebase에 인증하는 방법은 다음과 같습니다.
- Google 계정으로 사용자를 로그인하고 사용자의 Google ID 토큰을 가져옵니다. 여기에는 몇 가지 방법이 있습니다. 예를 들면 다음과 같습니다.
- 앱에 브라우저 프런트엔드가 있는 경우 수동으로 로그인 과정 처리 섹션의 설명에 따라 Google 로그인을 사용합니다. 인증 응답에서 Google ID 토큰을 가져옵니다.
그런 다음 이 토큰을 Node.js 앱에 전송합니다.var id_token = googleUser.getAuthResponse().id_token
- TV와 같이 입력 기능이 제한된 기기에서 앱을 실행하는 경우 TV 및 기기용 Google 로그인 과정을 사용할 수 있습니다.
- 앱에 브라우저 프런트엔드가 있는 경우 수동으로 로그인 과정 처리 섹션의 설명에 따라 Google 로그인을 사용합니다. 인증 응답에서 Google ID 토큰을 가져옵니다.
- 사용자의 Google ID 토큰을 가져온 후, 해당 토큰으로 사용자 인증 정보 객체를 만들고 이 객체로 사용자를 로그인합니다.
import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth"; // Build Firebase credential with the Google ID token. const credential = GoogleAuthProvider.credential(id_token); // Sign in with credential from the Google user. const auth = getAuth(); 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 = GoogleAuthProvider.credentialFromError(error); // ... });
// Build Firebase credential with the Google ID token. var credential = firebase.auth.GoogleAuthProvider.credential(id_token); // Sign in with credential from the Google 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; // ... });
Chrome 확장 프로그램에서 Firebase로 인증
Chrome 확장 프로그램 앱을 빌드하는 경우에는 오프스크린 문서 가이드를 참조하세요.
Google 로그인을 위한 리디렉션 도메인 맞춤설정하기
프로젝트를 만들 때 Firebase에서는 프로젝트의 고유한 하위 도메인(https://my-app-12345.firebaseapp.com
)을 프로비저닝합니다.
이 도메인은 OAuth 로그인을 위한 리디렉션 메커니즘으로도 사용됩니다. 이 도메인은 지원되는 모든 OAuth 제공업체에 대해 허용되어야 합니다. 하지만 이로 인해 사용자는 애플리케이션으로 다시 리디렉션되기 전에 Google에 로그인하는 과정에서 이 도메인을 볼 수 있습니다. 다음으로 이동: https://my-app-12345.firebaseapp.com
하위 도메인이 표시되지 않게 하려면 Firebase Hosting으로 커스텀 도메인을 설정하면 됩니다.
- Hosting용 도메인 설정의 1~3단계를 따릅니다. 도메인 소유권을 확인하면 Hosting에서 커스텀 도메인의 SSL 인증서를 프로비저닝합니다.
- Firebase Console에서 승인된 도메인 목록에 커스텀 도메인
auth.custom.domain.com
을 추가합니다. - Google 개발자 콘솔 또는 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. });