1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue.jsでGoogle認証を組み込む

Last updated at Posted at 2022-01-03

前回(https://www.mkhs.work/wordpress2/?p=274)Google Firebaseでソーシャル認証の設定を行いました。今回はVue.jsでGoogle認証の組込みを行います。コンポーネントのサンプルは下記です。

<template>
  <div>
    <button class="btn btn-secondary" v-on:click="authMethod">
      認証
    </button>
    <p class="h5">
      {{ data.email_address }}
    </p>
  </div>
</template>
<script>
import { reactive} from 'vue'
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
export default {
props:{
},
setup(){
const authMethod = ()=> {
  const firebaseConfig = {apiKey: &quot;XXXXX&quot;, 
                          authDomain: &quot;XXXXX&quot;,
                          databaseURL: &quot;XXXXX&quot;,
                          projectId: &quot;XXXXX&quot;,
                          torageBucket: &quot;XXXXX&quot;,
                          messagingSenderId: &quot;XXXXX&quot;,
                          appId: &quot;XXXXX&quot;,
                          measurementId: &quot;XXXXX&quot;}
  initializeApp(firebaseConfig);                            
 
  const provider = new GoogleAuthProvider()
  const auth = getAuth();
  signInWithPopup(auth, provider).then((result) =&gt; {
    const user = result.user
    data.email_address = user.email
  }).catch((error) =&gt; {
    const errorCode = error.code
    const errorMessage = error.message
    const email = error.email
    console.log(&#39;errorCode: &#39; + errorCode + &#39;/errorMessage: &#39; + errorMessage + &#39;/email: &#39;+ email)
  })
}

  const data = reactive({
    email_address: &#39;&#39;
  })
  return {
    data, authMethod
  }
}

}
</script>

XXXXXは伏字です。伏字部分はプロジェクトの設定画面で確認できます。

image.png

また、下図の通りコードのサンプルがありますので、コピペできて便利です。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/146872/eafbf657-339a-1290-24b7-9e2701e65c8d.png)

サンプルでは、認証ボタン押下でGoogleのアカウント選択画面が現れ。。。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/146872/4c34eadc-1b5b-bc53-1620-75983d7a040a.png)

ログインするアカウントを選択すると、認証したユーザーのメールアドレスを表示します。

image.png

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?