BESPIN Tech Blog
  • Home
  • Tech
    • CSP

      AWS

      GCP

      NCP

      Cloud

      Migration

      LZ, Control Tower

      Backup

      Monitoring

      Container

      Infra

      OS

      Middleware

      Data

      RDB

      Big Data Platform

      Application

      CI/CD

      BESPICK 구독하기 ㅣ 1668-1280

  • Trend
  • IT
최신 리포트 다운로드 지금 바로 문의하기
BESPIN Tech Blog
  • Home
  • Tech
    • CSP

      AWS

      GCP

      NCP

      Cloud

      Migration

      LZ, Control Tower

      Backup

      Monitoring

      Container

      Infra

      OS

      Middleware

      Data

      RDB

      Big Data Platform

      Application

      CI/CD

      BESPICK 구독하기 ㅣ 1668-1280

  • Trend
  • IT
최신 리포트 다운로드 지금 바로 문의하기
BESPIN Tech Blog
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
TECHCSPGCP

Firebase Google Login

by 형래 김 2024년 02월 02일
2024년 02월 02일
23

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

감사합니다 🙂

관련

localhostFirebase Google LoginES6+HTMLJavaScriptFirebaseAuthenticationmethodSign-inbrowserLaunchvscodePreviewFireFox구글

HOT Trend

Recent Posts

  • 딜로이트도, 맥킨지도, 베스핀글로벌도: AI 에이전트로 일 바꾸는 시대

    2025년 07월 04일 클라우드베스핀글로벌clouddata데이터AI인공지능HelpNow AIbespinglobalAI에이전트helpnow업무자동화딜로이트
  • ⚔️데이터센터에서 시작된 전쟁? 요즘 뜨는 AIDC 개념부터 트렌드까지!

    2025년 06월 27일 클라우드clouddata데이터AI데이터센터클라우드 데이터센터bespinglobalAIDCAI 인프라베스핀글로벌
  • 구글부터 엔비디아까지, 빅테크 기업들의 AI 전략 최신본📖

    2025년 06월 20일 cloud베스핀글로벌클라우드data데이터AI구글마이크로소프트엔비디아AI에이전트google I/ONVIDIA GTC 2025Microsoft build 2025
  • AI를 연결한다고? 업계가 주목하는 ‘MCP’ 알아보기🔍

    2025년 06월 13일 베스핀글로벌클라우드cloudAIMCP
  • [WhaTap] RDS Failover/Reboot 관제 2 – RDS Failover

    2025년 05월 30일 RDSRDS FailoverRebootFailoverbespin global

베스핀글로벌은 모든 기업의 AI 혁신을 실현하기 위해, 세상에서 가장 혁신적이고 자동화된 AI 서비스와 솔루션을 만들어갑니다.
상호 : 베스핀글로벌 주식회사 ㅣ 대표자명 : 김써니, 허양호 ㅣ 사업자등록증번호 : 638-87-00223 ㅣ 통신판매번호 : 2019-서울서초-0347 ㅣ 대표전화 : 1668-1280
사업장주소지 : 서울특별시 서초구 강남대로 327, 13,14,15,16층(서초동,대륭서초타워) ㅣ 이메일 : info@bespinglobal.com ㅣ 개인정보 처리방침 ㅣ 개인정보 처리방침 안내

© 2026 BESPIN GLOBAL, All Rights Reserved.

BESPINGLOBAL
패밀리 사이트
China MEA SEA US

BESPIN Tech Blog
  • Home
  • Tech
    • CSP

      AWS

      GCP

      NCP

      Cloud

      Migration

      LZ, Control Tower

      Backup

      Monitoring

      Container

      Infra

      OS

      Middleware

      Data

      RDB

      Big Data Platform

      Application

      CI/CD

      BESPICK 구독하기 ㅣ 1668-1280

  • Trend
  • IT