Skip to content
BESPIN Tech Blog
  • Tech
    • CSP
      • AWS
      • GCP
      • NCP
    • Cloud
      • Migration
      • LZ, Control Tower
      • Backup
      • Monitoring
      • Container
    • Infra
      • OS
      • Middleware
    • Data
      • RDB
      • Big Data Platform
    • Application
      • CI/CD
  • Trend
  • IT
  • Contact US

Firebase Google Login

2024년 02월 02일 by 형래 김

1. 개요


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

2. 내용


  1. 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

감사합니다 🙂

이 글 공유하기:

  • X에 공유 (새 창에서 열림) X
  • Facebook으로 공유하기 (새 창에서 열림) Facebook
  • LinkedIn에 공유 (새 창에서 열림) LinkedIn

관련글

Categories TECH, CSP, GCP Tags localhost, Firebase Google Login, ES6+, HTML, JavaScript, Firebase, Authentication, method, Sign-in, browser, Launch, vscode, Preview, FireFox, 구글
[베스픽] 복잡한 제조 공정을 효율적으로 통합하는 이것, 6년 뒤면 1,000조 원 시장?
[베스픽] RAG? STT? 생성형 AI 용어 친절히 다 모았습니다

Copyright ⓒ 2024 BESPIN GLOBAL

대표번호: 02-1668-1280

info@bespinglobal.com

© 2026 BESPIN Tech Blog • Built with GeneratePress