본문 바로가기

개발/javascript

[React] Firebase Auth기능을 이용한 로그인 구현 - Google/Github/Email

Preparation

1. Firbase console에서 새 project 및 web app 생성

2. 코드 작업환경 설정, firebase initializeApp

더보기

1. firebase console에서 project 생성

https://console.firebase.google.com/

 

로그인 - Google 계정

이메일 또는 휴대전화

accounts.google.com

2. 생성한 프로젝트 진입하여 웹앱 추가

3. npm library : 개발환경에 firebase 설치(현재 최신버전인 v9 사용)

npm install firebase

4. firebase initializeApp : 웹앱 생성시의 가이드를 따라 진행([설정 - 내 앱 - SDK 설정 및 구성] 에서도 확인가능)

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// 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: "AIzaSyAwZzqb2xGvdwOAMNGERni4pGsAkUg6Wr4",
  authDomain: "test-project-ae008.firebaseapp.com",
  projectId: "test-project-ae008",
  storageBucket: "test-project-ae008.appspot.com",
  messagingSenderId: "132963492567",
  appId: "1:132963492567:web:bb6b26c2072a3463688692"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

 

 

Firebase Console 설정

1. Firebase Console에서 web project 선택하여 프로젝트 페이지 진입

2. 왼쪽 사이드바 > 빌드탭 > Authentication 선택

3. 시작하기 버튼 선택

4. 어떤 매체로부터 로그인이 가능하도록 허용할 것인지 설정

    (이 글에서는 이메일/비밀번호, Google, Github을 이용할 것임)

 

4-1. 이메일/비밀번호

사용설정 ON

 

4-2. Google

사용설정 ON, 본인 이메일 등록

 

4-3. Github

1) 사용설정 ON -> 하단에 callback URL이 생성됨

2) github 페이지로 이동하여 OAuth Apps 생성

  • github > Setting > Developer settings > OAuth Apps > Register a new application

  • callback URL은 firebase console에서 생성된 것 복사하여 사용

3) OAuth Apps 생성 후, clientID 아래의 Generate a new client secret 버튼 선택

4) clientID 및 생성된 secret 복사하고 firebase console로 돌아가서 붙여넣기 후 저장

 

Code

Firebase auth package에 있는 여러 함수들 중, 사용빈도가 높을것 같은 함수들을 간단하게 정리해 보았습니다.

 

우선 initialized app 객체를 파라미터로하여 getAuth 함수를 사용할 수 있으며,

이 글에서 사용할 모든 함수들은 getAuth 에서 반환되는 auth 인스턴스를 필요로합니다. 

import { getAuth } from "firebase/auth";

//...

const app = initializeApp(firebaseConfig);
const authService = getAuth(app);

 

이메일로 계정 생성

import { createUserWithEmailAndPassword } from "firebase/auth";

//inside async function
const data = await createUserWithEmailAndPassword(authService, email, password)

createUserWithEmailAndPassword함수가 동작된 후, Firebase console > Authentication > Users에서 추가된 유저를 확인할 수 있습니다.

 

 

이메일/패스워드로 로그인

import { signInWithEmailAndPassword } from "firebase/auth";

//inside async function
data = await signInWithEmailAndPassword(authService, email, password);

계정이 생성된 후에는, signInWithEmailAndPassword 함수를 호출하여 로그인처리를 할 수 있습니다. 

 

구글 계정으로 로그인

import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";

//inside async function
const provider = new GoogleAuthProvider();
await signInWithPopup(authService, provider);

GoogleAuthProvider생성 후, 이 provider를 파라미터로 signInWithPopup를 호출해주면 바로 Google계정으로 로그인이 가능합니다. SignIn~ 함수들은 UserCredential를 반환하는데, UserCredential.user로 로그인된 사용자 객체를 확인할 수 있습니다.

* GoogleAuthProvider 이외에도 GithubAuthProvider, PhoneAuthProvider, TwitterAuthProvider 등의 provider가 있으며, 모두 같은 방식으로 사용이 가능합니다. 

 

깃헙 계정으로 로그인

import { GithubAuthProvider, signInWithPopup } from "firebase/auth";

//inside async function
const provider = new GithubAuthProvider();
await signInWithPopup(authService, provider);

 

로그인 상태 확인

 

import { onAuthStateChanged } from "firebase/auth";

onAuthStateChanged(authService,(user)=>{ 
  if(user){
    setLoggedInFlag(true);
  } else {
    setLoggedInFlag(false);
  }
});

onAuthStateChanged를 통해 간편하게 User login 상태변화를 감지할 수 있습니다.

 

로그아웃

import { signOut } from "firebase/auth";

//inside async function
signOut(authService);

signOut 함수를 호출해주면, 현재 계정에서 log out됩니다.

 

 

Reference

https://firebase.google.com/docs/reference/js/auth?hl=ko&authuser=0 

 

auth package  |  Firebase JavaScript API reference

 

firebase.google.com