1. 개요
Firebase를 이용한 Google Login를 정리합니다.
소스 : HTML, JavaScript ES6+(IE 미지원)
기본 Spark 요금제는 일정 사용량은 무료입니다. 특히 Authentication 한국은 완전 무료입니다.
2. 내용

- firebase.google.com 접속, ‘콘솔로 이동’ 클릭

2. ‘프로젝트 만들기’

3. 프로젝트 이름 입력

4. 약관 동의 후 ‘계속

5. 애널리틱스 화면 확인

6. 애널리틱스 사용하지 않고 ‘프로젝트 만들기’

7. 프로젝트 준비가 끝나면 ‘계속

8. </> 버튼 클릭

9. 웹 앱에 Firebase 추가 화면 확인

10. 앱 닉네임 입력

11. ‘<script> 태그 사용’ 선택

12. ‘다음’

13. ‘다음’

14. ‘콘솔로 이동’

15. ‘앱 1개’

16. Authentication 화면에서 ‘시작하기’

17. Sign-in method 탭에서 ‘Google’ 선택

18. ‘사용 설정’

19. ‘프로젝트의 공개용 이름’ 및 ‘프로젝트 지원 이메일’ 선택, 확인 그리고 ‘저장’

20. ‘Google’ 상태 확인 및 ‘localhost’ 도메인 확인

21. ‘프로젝트 설정’

22. 해당 내용 참고. 실제 소스와 다르면 에러 발생.

23. vscode에서 ‘Preview on Web Server’ Extension 설치. ‘Launch on browser’ 단축키 확인.

24. 소스 확인 후 단축키(ctrl+shift+l)로 Preview on Web Server 실행
3. 최종 소스
github : https://github.com/KimYunBeom/kdb/tree/main/firebase-google-login
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Firebase Google Login</title>
<style>
.hide {
display: none;
}
</style>
</head>
<body>
<div>
<a href="#">
<img src="./btn_google_signin_dark_normal_web.png" alt="구글 이미지" id="googleLoginButton" />
</a>
</div>
<div>
<button type="button" id="googleLogoutButton" class="hide">로그아웃</button>
</div>
<hr />
<div id="result" class="hide">
<div><span>uid : </span><span id="resultUid"></span></div>
<div><span>email : </span><span id="resultEmail"></span></div>
<div><span>name : </span><span id="resultName"></span></div>
<div>
<div>photo :</div>
<img id="resultPhoto" src="http://picsum.photos/96" alt="랜덤 이미지" />
</div>
<div><span>created : </span><span id="resultCreated"></span></div>
<div><span>last login : </span><span id="resultLastLogin"></span></div>
</div>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js';
import {
GoogleAuthProvider,
getAuth,
signInWithPopup,
signOut,
setPersistence,
} from 'https://www.gstatic.com/firebasejs/9.8.1/firebase-auth.js';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: 'YOUR_INFORMATION',
authDomain: 'YOUR_INFORMATION',
projectId: 'YOUR_INFORMATION',
storageBucket: 'YOUR_INFORMATION',
messagingSenderId: 'YOUR_INFORMATION',
appId: 'YOUR_INFORMATION',
measurementId: 'YOUR_INFORMATION',
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const provider = new GoogleAuthProvider();
const auth = getAuth();
const requestLogin = () => {
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;
console.log('user :\n', JSON.stringify(user, null, 2));
const {
uid,
email,
displayName,
photoURL,
metadata: { creationTime },
metadata: { lastSignInTime },
} = user; // Destructuring Assignment. Object and nested object.
document.querySelector('#resultUid').textContent = uid;
document.querySelector('#resultEmail').textContent = email;
document.querySelector('#resultName').textContent = displayName;
document.querySelector('#resultPhoto').setAttribute('src', photoURL);
document.querySelector('#resultCreated').textContent = creationTime;
document.querySelector('#resultLastLogin').textContent = lastSignInTime;
document.querySelector('#result').classList.remove('hide');
document.querySelector('#googleLogoutButton').classList.remove('hide');
})
.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 AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
console.log(errorCode, errorMessage);
});
};
const requestLogout = () => {
signOut(auth)
.then(() => {
window.location.assign('https://accounts.google.com/logout');
})
.catch((error) => {
alert('로그아웃에 실패했습니다.');
});
};
const initElemEvent = () => {
googleLoginButton.addEventListener('click', () => {
requestLogin();
});
googleLogoutButton.addEventListener('click', () => {
requestLogout();
});
};
const init = () => {
initElemEvent(); // 초기화 : Element 이벤트
};
init();
</script>
</body>
</html>

25. 실행된 화면 확인, 이미지 버튼 클릭

26. 이미 로그인 된 경우, 팝업에서 추가 인증 없이 바로 브라우저에서 로그인 결과 출력. ‘로그아웃’

27. 로그아웃 화면, 크롬 웹 브라우저의 프로필도 동시에 일시중지됨

28. FireFox 웹 브라우저에서 테스트 화면 다시 접근. 로그아웃 확인

29. 로그인 시도, 이메일과 비밀번호를 입력하여 다시 진행

30. 로그인 확인. ‘로그아웃’

31. 크롬과 다른 로그아웃 화면 확인
4. 참고URL
- 구글 로그인 브랜드 가이드라인
https://developers.google.com/identity/branding-guidelines?hl=ko
- Firebase Web 가이드
https://firebase.google.com/docs/web/setup?hl=ko
- Firebase Web Sign Out 가이드
https://firebase.google.com/docs/auth/web/password-auth?hl=ko
감사합니다 🙂