[React] Firebase auth 서비스를 이용하여 회원가입/로그인 구현하기

roses16·2023년 4월 17일
0

Firebase

📌 https://firebase.google.com/

Firebase는 모바일 및 웹 어플리케이션을 만들기 위한 여러 기능을 지원하는 서비스이다. 주요 기능으로는 noSql 기반의 database, 회원가입/로그인 기능을 위한 Authentication 등이 있다.
Back-end 코드 없이 1인 포트폴리오를 만들기 위해 사용하였으나 일반적으로 실제 서비스에서는 사용되지 않는다.


install & initialize

  1. Firebase 및 React 프로젝트를 생성한다.

  2. Web, App, Flutter 등 프로젝트에 맞는 Firebase App을 생성한다.

  3. React 내 Firebase를 설치한다.
    <script> 태그로 사용할 수 있으나 연습 때에는 yarn add firebase 로 설치

  4. Firebase App 생성 시 아래 코드와 같은 정보를 제공한다.
    React 내 해당 js파일을 작성한다.

    // src/firebaseInstance.js
    import { initializeApp } from "firebase/app";
    
    const firebaseConfig = {
      apiKey: "",
      authDomain: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: "",
      appId: ""
    };
    
    const firebaseInstance = initializeApp(firebaseConfig);
    
    export default firebaseInstance;
  1. src/index.js 파일에 import 한다.

Auth Interface

Firebase Auth 서비스를 사용할 수 있게 하는 인터페이스.
현재 인증된 유저 정보 접근, 유저 정보 업데이트 등 인증과 관련된 작업이 가능하다.

- Firebase service setup

  1. 생성된 Firebase App 내 'Authentication' 메뉴에서 해당 서비스의 사용 여부를 설정한다.
  2. 'Sign-in-method' 메뉴에서 사용할 인증 방식을 선택한다.

- React에서 사용하기

instance와 method
📌 https://firebase.google.com/docs/reference/js/auth.auth

  • Interface 생성
    getAuth() 함수를 통해 Auth 인터페이스를 생성한다.
    // src/firebaseInstance.js
    import { getAuth } from "firebase/auth";
    // ...
    // firebase initialize
    // ...
    export const authService = getAuth(firebaseInstance);

- sign up, sign in

아래 예시의 method는 E-mail&Password 방식이다. Firebase에서 선택한 auth service 종류에 따라 method가 다르다. promise객체를 반환하는 비동기 method이다.

  • createUserWithEmailAndPassword()
    sign up에 사용하는 method

    // firebaseInstance.js
    import { createUserWithEmailAndPassword } from "firebase/auth";
    
    export function createUser(email, password){
    return createUserWithEmailAndPassword(authService, email, password);
    }
  • signInWithEmailAndPassword()
    sign in에 사용하는 method

    import { signInWithEmailAndPassword } from "firebase/auth";
    
    export function signInUser(email, password){
    return signInWithEmailAndPassword(authService, email, password);
    }

profile
frontend developer 📚

0개의 댓글