웹사이트에서 Firebase 인증 시작하기

Firebase 인증을 사용하면 사용자가 이메일 주소와 비밀번호 로그인 및 제휴 ID 제공업체(예: Google 로그인, Facebook 로그인)를 비롯한 1개 이상의 로그인 방법을 사용해 앱에 로그인할 수 있습니다. 이 튜토리얼에서는 Firebase 인증을 시작할 수 있도록 앱에 이메일 주소와 비밀번호를 통한 로그인을 추가하는 방법을 보여줍니다.

Authentication SDK 추가 및 초기화

  1. 아직 진행하지 않았다면 Firebase JS SDK를 설치하고 Firebase를 초기화합니다.

  2. Firebase 인증 JS SDK를 추가하고 Firebase 인증을 초기화합니다.

웹 모듈식 API

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

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


// Initialize Firebase Authentication and get a reference to the service
const auth = getAuth(app);

웹 네임스페이스화된 API

import firebase from "firebase/compat/app";
import "firebase/compat/auth";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Firebase Authentication and get a reference to the service
const auth = firebase.auth();

(선택사항) Firebase 로컬 에뮬레이터 도구 모음으로 프로토타입 제작 및 테스트

앱에서 사용자를 인증하는 방법을 설명하기 전에 인증 기능의 프로토타입을 제작하고 테스트하는 데 사용할 수 있는 도구 모음인 Firebase 로컬 에뮬레이터 도구 모음을 소개하겠습니다. 사용할 인증 기술과 제공업체를 결정하거나, 인증 및 Firebase 보안 규칙을 사용하는 공개 및 비공개 데이터가 포함된 다양한 데이터 모델을 사용해 보거나, 로그인 UI 디자인의 프로토타입을 제작하는 경우 라이브 서비스를 배포하지 않고 로컬에서 작업할 수 있다는 것은 획기적인 아이디어입니다.

인증 에뮬레이터는 로컬 에뮬레이터 도구 모음의 일부이며 앱에서 에뮬레이션된 데이터베이스 콘텐츠와 구성은 물론 필요에 따라 에뮬레이션된 프로젝트 리소스(함수, 기타 데이터베이스, 보안 규칙)와 상호작용할 수 있게 해줍니다.

인증 에뮬레이터를 사용하려면 다음 몇 단계만 거치면 됩니다.

  1. 에뮬레이터에 연결하려면 앱의 테스트 구성에 코드 줄을 추가합니다.
  2. 로컬 프로젝트 디렉터리의 루트에서 firebase emulators:start를 실행합니다.
  3. 대화형 프로토타입 제작에는 로컬 에뮬레이터 도구 모음 UI를, 비대화형 테스트에는 인증 에뮬레이터 REST API를 사용합니다.

자세한 안내는 인증 에뮬레이터에 앱 연결을 참조하세요. 자세한 내용은 로컬 에뮬레이터 도구 모음 소개를 참조하세요.

이제 사용자 인증 방법을 계속 살펴보겠습니다.

신규 사용자 가입

신규 사용자가 자신의 이메일 주소와 비밀번호를 사용해 앱에 가입할 수 있는 양식을 만듭니다. 사용자가 양식을 작성하면 사용자가 입력한 이메일 주소와 비밀번호의 유효성을 검사한 후 createUserWithEmailAndPassword 메서드에 전달합니다.

웹 모듈식 API

import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";

const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in 
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

웹 네임스페이스화된 API

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Signed in 
    var user = userCredential.user;
    // ...
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ..
  });

기존 사용자 로그인

기존 사용자가 자신의 이메일 주소와 비밀번호를 사용해 로그인할 수 있는 양식을 만듭니다. 사용자가 양식을 작성하면 signInWithEmailAndPassword 메서드를 호출합니다.

웹 모듈식 API

import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in 
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });

웹 네임스페이스화된 API

firebase.auth().signInWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Signed in
    var user = userCredential.user;
    // ...
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
  });

인증 상태 관찰자 설정 및 사용자 데이터 가져오기

로그인한 사용자에 대한 정보가 필요한 앱 페이지마다 전역 인증 객체에 관찰자를 연결합니다. 사용자의 로그인 상태가 변경될 때마다 이 관찰자가 호출됩니다.

onAuthStateChanged 메서드를 사용해 관찰자를 연결합니다. 사용자가 로그인되면 관찰자에서 사용자에 대한 정보를 가져올 수 있습니다.

웹 모듈식 API

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/auth.user
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

웹 네임스페이스화된 API

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/v8/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

다음 단계

다른 ID 공급업체 및 익명 게스트 계정에 대한 지원을 추가하는 방법을 알아보세요.