Google로 사용자 로그인
이 문서에서는 Identity Platform을 사용하여 Google로 사용자를 로그인 처리하는 방법을 보여줍니다.
시작하기 전에
이 튜토리얼에서는 Identity Platform을 이미 사용 설정했으며 HTML 및 자바스크립트를 사용하여 작성된 기본 웹 앱이 있다고 가정합니다. Identity Platform을 사용 설정하고 로그인하는 방법을 알아보려면 빠른 시작을 참고하세요.
Google을 공급업체로 구성
Google을 ID 공급업체로 구성하려면 다음 단계를 따르세요.
- Google Cloud 콘솔에서 ID 공급업체 페이지로 이동합니다.
- 공급업체 추가를 클릭합니다.
- 목록에서 Google을 선택합니다.
- Google 웹 클라이언트 ID와 웹 보안 비밀을 입력합니다. 아직 ID와 보안 비밀이 없으면 API 및 서비스 페이지에서 얻을 수 있습니다.
- 외부 클라이언트 ID의 액세스를 허용하려면 추가를 클릭하고 클라이언트 ID를 추가합니다.
- 동의 화면을 구성하려면 화면 구성을 클릭합니다. 별도의 탭에서 Google 인증 플랫폼 페이지가 열립니다.
- Google 인증 플랫폼 페이지에서 OAuth 동의 화면을 구성합니다.
-
ID 공급업체 페이지로 돌아가 프로젝트 설정 측면 창에서 도메인 추가를 클릭하고 앱의 도메인을 추가합니다.
프로덕션 프로젝트에는
localhost
를 포함하지 않는 것이 좋습니다. - 애플리케이션 구성 섹션에서 설정 세부정보를 클릭합니다. 스니펫을 앱 코드에 복사하여 Identity Platform 클라이언트 SDK를 초기화합니다.
- 저장을 클릭합니다.
클라이언트 SDK로 사용자 로그인
-
Google 제공업체 객체의 인스턴스를 생성합니다.
웹 버전 9
import { GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider();
웹 버전 8
var provider = new firebase.auth.GoogleAuthProvider();
-
선택사항: OAuth 범위를 추가합니다. 범위는 Google에서 요청할 데이터를 지정합니다. 더 민감한 정보에는 특정 범위가 필요할 수 있습니다. 앱에 필요한 범위를 확인하려면 공급업체의 문서를 참조하세요.
웹 버전 9
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
웹 버전 8
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
-
선택사항: 인증 흐름을 현지화합니다. 언어를 지정하거나 기기의 기본 언어를 사용할 수 있습니다.
웹 버전 9
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
웹 버전 8
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
-
선택사항: 추가적인 커스텀 OAuth 매개변수를 지정합니다. 이는 Google에만 해당되며 일반적으로 인증 환경을 맞춤설정하는 데 사용됩니다. OAuth 또는 Identity Platform에서 예약한 매개변수는 전달할 수 없습니다.
웹 버전 9
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
웹 버전 8
provider.setCustomParameters({ 'login_hint': 'user@example.com' });
-
Google 공급업체 객체를 사용하여 사용자를 로그인 처리합니다. 팝업 창을 열거나 현재 페이지를 리디렉션할 수 있습니다. 휴대기기에서는 사용자가 리디렉션하기 더 용이합니다.
signInWithPopup()
을 호출하면 팝업이 나타납니다.웹 버전 9
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); // ... });
웹 버전 8
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
,linkWithRedirect
,reauthenticateWithRedirect
를 사용할 때는 권장사항을 따르세요.웹 버전 9
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
웹 버전 8
firebase.auth().signInWithRedirect(provider);
그런 다음 페이지가 로드될 때
getRedirectResult()
를 호출하여 Google 토큰을 검색합니다.웹 버전 9
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); // ... });
웹 버전 8
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; // ... });
액세스 토큰이 있으면 이를 사용하여 Google API를 호출할 수 있습니다. 예를 들면 다음과 같습니다.
REST
curl -H "Authorization: Bearer [TOKEN]" https://www.googleapis.com/oauth2/v2/userinfo
수동으로 사용자 로그인
클라이언트 SDK를 사용하지 않으려면 로그인 과정을 수동으로 처리할 수도 있습니다.
- 개발자 문서의 단계에 따라 Google 인증을 앱에 통합합니다.
- 이전 단계에서 구현한 흐름을 사용하여 Google에 사용자를 로그인 처리합니다.
-
Google에서 수신한 토큰을 Identity Platform 사용자 인증 정보로 교환합니다.
웹 버전 9
import { GoogleAuthProvider } from "firebase/auth"; const credential = GoogleAuthProvider.credential(idToken);
웹 버전 8
var credential = firebase.auth.GoogleAuthProvider.credential(idToken);
-
사용자 인증 정보를 사용하여 Identity Platform으로 사용자를 로그인합니다.
웹 버전 9
import { getAuth, signInWithCredential } from "firebase/auth"; // Sign in with the credential from the user. const auth = getAuth(); signInWithCredential(auth, credential) .then((result) => { // Signed in // ... }) .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; // ... });
웹 버전 8
// Sign in with the credential from the user. firebase.auth() .signInWithCredential(credential) .then((result) => { // Signed in // ... }) .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; // ... });
다음 단계
- Identity Platform 사용자에 대해 자세히 알아보세요.
- 다른 ID 공급업체로 사용자를 로그인 처리합니다.