본문 바로가기
React/E-commers App

의류 쇼핑몰 15 | 구글 계정으로 로그인 | Authentication with Firebase

by CodeMia 2022. 6. 6.

Firebase api와 내 웹이 교류하여 구글 계정으로 로그인을 해보자. 

 

 

구글 로그인 버튼 만들기 

일단은 routes 폴더에 sign-in.jsx 을 파일을 만든다. 

구글 로그인 버튼을 추가하였다. 

 

 

 

만든 화면은 다음과 같다.

 

이제는 Google Sign In 버튼을 눌렀을 때

구글 api가 연결되어 구글 로그인 페이지가 뜨도록 해보자. 

 


 

1.  firebase 와 내 웹 연결하기 

1. firebase에서 내 웹 instance 만들기  

firebase와 내 웹을 연결해야 한다.

firebase에서 config를 받아와 내 웹 코드에 붙이면 된다. 

 

1. 내 app 등록을 한다.

구글 firebase 프로젝트 안으로 들어가서 </> 버튼을 누른다. 

 

 

원하는 이름을 입력하고 Register app 버튼을 누른다. 

Hosting은 클릭하지 않는다. 

 

 

2. 아래와 같은 화면이 나오는데 순서대로 실행한다. 

 

2-1 터미널에 firebase를 다운받기 

npm install firebase 

 

2-2  config 코드 패키지를 복사해서 firebase.utils.js 파일에 붙여넣기 할 것이다.

 

2. auth를 연결하기 

1. 파일 만들기 

utils 로 새폴더를 만들어 백엔드 관련 코드를 담아보자. 

utils-firebase-firebase.utils.js 새 자바스크립트 파일을 만든다.

 

 

 

2. 복사한 config를 붙여 넣기한다. 

 

Line 1:

 import { initializeApp } from 'firebase/app

많은 firebase 라이브러리(tool) 중에서 app library를 import한다.

또 그 중에서 { initializeApp } 즉 App function을 initialize 한다. 

이 initializeApp funtion이 config를 바탕으로 app instance를 만든다.

 

Line 3: 

firebaseConfig : 이 Firebase app instance를 온라인에 있는 firebase instance에 붙이는 일을 한다. 

 

Line 12: 

const app = initializeApp(firebaseConfig); 

initializeApp 함수는 firebaseConfig를 바탕으로 app instance를 만든다. 

firebase에 있는 instance와 interact 하기 위해 사용된다. 

 

firebase에서 받은 firebaseConfig를 넣어주어

app instance 에서 app 확인과 어떤 db인지, CRUD 액션들 creating, reading, updating, storing, authenticating 등의 일을 한다. 

 

 

app을 firebaseApp으로 좀 더 명확한 이름으로 바꿔주었다.

 


 

2. Firebase에서 Sign-in method로 구글 선택 

 

이제는 구글 콘솔로 가서 어떤 provider로 sign-in을 정한다. 

Authentication->  Sign-in method -> Add new provider를 가서 

Facebook, Apple 등 원하는 Sign-in provider를 선택할 수 있다.

 

 

 

일단은 Google을 선택했다. 

 

 

google sign-in enable 하기 

 

 


 

3.  구글 provider 연결하기 

(문서)

 

1. Create an instance of the Google provider object 

firebase doc

 

GoogleAuthProvider는 firebase authentication에서 온 class이다. 

Google auth에 있는 여러 implementation들 중 firebase Google auth와 연결이 된다. 

 

provider는 다양한 종류로 여러 개가 있을 수 있다. (google, facebook..)

authentication은 단독 개체로 firebase와 통신할 때 어디에 있든 항상 같다. 

Once you authenticate for this website as a whole, it should be held onto for the duration of the lifecyle of this application. 그래서 여러개의 provider는 있지만 1개 이상의 authentication은 필요없다. 

 

 

1-2 나중에 facebook등 다른 provider도 추가될 수 있으니 

provider를 googleProvider로 고쳐준다. 

 

 

 

2. 구글 계정 선택 

구글 계정이 여러 개 일 수 있으니 로그인할 계정을 선택하게 한다. (문서1, 문서2)

언제든지 provider를 interact 하면 select account를 선택하도록 하였다.

setCustonParameters는 환경설정 할 수 있게 한 키워드이다. 

 

 

 

 

 

3. 구글 pop-up 으로 나오게 하기 

윈도우는 pop-up

모바일은 redirect

getAuth로 authentication을 시작한다. 

Firebase는 한 개의 라이브러리가 아니라 많은 micro library 패키지가 모여 있다.

그 중에 하나는 authentication과 관한 것이다. 

firebase/auth에서 라이브러리들을 import한다.

 

import { initializeApp } from "firebase/app";
import {
getAuth,
signInWithRedirect,
signInWithPopup,
GoogleAuthProvider,
} from 'firebase/auth';
 

const firebaseConfig = {
apiKey: "AIzaSyD5u1b7NlJvSngl9dBDPtr6Exe9OtPJhVM",
authDomain: "crown-clothing-db-9557d.firebaseapp.com",
projectId: "crown-clothing-db-9557d",
storageBucket: "crown-clothing-db-9557d.appspot.com",
messagingSenderId: "250438021523",
appId: "1:250438021523:web:f24454411dcae8ff53b866"
};

const firebaseApp = initializeApp(firebaseConfig);

const googleProvider = new GoogleAuthProvider();

googleProvider.setCustomParameters({
prompt: 'select_account'
});

export const auth = getAuth();
export const signInWithGooglePopup = () => {
signInWithPopup(auth, googleProvider);
}

 


 

4. sign-in 페이지 작업

sign-in component로 가서 구글 로그인 버튼 누르면 

구글 팝업이 뜨도록 해보자. 

 

firebase.utils.js에서 export한 내용을 sign-in으로 가져온다.  

 

 

logGoogleUser 함수를 async로 만들고, 

버튼 클릭이 되었을 때 호출 되도록 한다. 

import { signInWithGooglePopup } from '../../utils/firebase/firebase.utils';

const SignIn = () => {

const logGoogleUser = async () => {
const response = await signInWithGooglePopup();
console.log(response)
}
return (
<div>
<h1>Sign In Page</h1>
<button onClick={logGoogleUser}>Google Sign In</button>
</div>
);
};

export default SignIn;

 

 


결과 확인 

 

구글 Sign in 버튼을 클릭하면 

 

 

수업에서는 새 팝업이 뜨는데

난 새로운 창이 뜨면서 이메일을 선택하라고 나온다. 

이메일을 선택하면 페이지도 사라진다. 

 

Firebase authentication에 가면  로그인한 유저의 목록이 나와있다.

 


 

유저 access token 확인 

앞 포스트 authentication flow를 설명했듯이

firebase에서 성공적으로 authentication이 이뤄지면 유저의 access_token을 준다. 

이 accessToken으로 이제 CRUD requests를 할 수 있다. 

 

 

 access_token을 확인해 보자. 

콘솔에서 보면 UserCredential 오브젝트를 볼 수 있다. 

 

 

user에 들어가면 accessToken을 볼 수있다. 

댓글