강디너의 개발 일지

javascript - firebase, google 로그인 with Vue.js 본문

Javascript/Vue.js

javascript - firebase, google 로그인 with Vue.js

강디너 2020. 11. 5. 01:37
728x90

목표

  1. Vue.js를 이용하여 firebase, google 로그인
  2. google AccessToken, RefreshToken 가져오기

 

Firebase

1. Firebase 프로젝트 설정에서 Google 로그인 사용 설정을 허용합니다.

 

2. Firebase SDK 설치 (현재 8.0.0 버전)

npm install --save firebase

 

3. Firebase 세팅 (firebase.google.com/docs/auth/web/google-signin)

 

Vue 컴포넌트가 생성 될 때 firebase 초기화 후  로그인 이벤트 설정해줍니다.

<template>
    <img
        src="@/assets/login/btn_google_signin_light_normal_web@2x.png"
        @click="loginWithGoogle"
    />
</template>
<script>
import firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = {
    apiKey: "AIzaSyB-------HN5jJ1ESA0w_--------Aw6nw",
    authDomain: "test-web-e8d37.firebaseapp.com",
    databaseURL: "https://test-web-e8d37.firebaseio.com",
    projectId: "test-web-e8d37",
    storageBucket: "test-web-e8d37.appspot.com",
    messagingSenderId: "390069637413",
    appId: "1:39-----------------a1a37c590acc",
};

export default {
    created() {
        firebase.initializeApp(firebaseConfig);
    },
    methods: {
        async loginWithGoogle() {
            console.log("login");
            const provider = new firebase.auth.GoogleAuthProvider();
            provider.setCustomParameters({
                prompt: "select_account",
            });
            const profile = await firebase.auth().signInWithPopup(provider);
            console.log(profile);
        },
    },
};
</script>

 

 

Google

1. 아래 구글 개발자 콘솔에서 프로젝트 생성 및 OAuth 2.0 클라이언트 ID를 얻습니다.

console.developers.google.com/

 

 

 

2. index.html 설정

developers.google.com/identity/sign-in/web/sign-in

Google javascript SDK + 구글 클라이언트 ID 설정해줍니다.

<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="18304878068-0rtpi00o0ifpho3irk306eimgi2fhq6a.apps.googleusercontent.com">

 

3. Google oauth2 login 세팅

google SDK에서는 로그인 성공 시 전역 함수를 호출하기 때문에 전역함수를 등록해줍니다.

<template>
    <div class="g-signin2" id="google-signin-btn" data-onsuccess="onSignIn" ></div>
</template>

<script>
export default {
    created() {
       window.onSignIn = this.onSignIn;
    },
    methods:{
        onSignIn (googleUser) {
            const profile = googleUser.getBasicProfile();
            console.log('ID Token: ', googleUser.getAuthResponse().id_token); // 실제 토큰
            console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
            console.log('Name: ' + profile.getName());
            console.log('Image URL: ' + profile.getImageUrl());
            console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        },
    }
}
</script>

문서에 적혀있듯이 ID값이 토큰이 아니니깐 백엔드로 보내지 말라고 합니다.

Token 값은 따로 있습니다.

 

후기.

자주 사용해봤어서 그런지 편안했다.

 

커피한잔...
Comments