LoginSignup
10
12

More than 3 years have passed since last update.

Nuxt.jsのプロジェクトにFirebase Authenticationによるユーザー認証を導入する方法

Last updated at Posted at 2019-08-09

Nuxt.jsのプロジェクトに、Firebase Authenticationによるユーザー認証を導入する方法を紹介します。

Firebaseでプロジェクトを作成

Firebase consoleから、プロジェクトを作成します。

Firebase Authenticationでログイン方法を設定

プロジェクトのAuthenticationから、ログイン方法を設定します。

https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/132608/775c95e9-7309-2c56-717b-79ab561c4c29.png

Firebase Authenticationでは、メールアドレスや電話番号などの基本的なものにくわえ、Google、Twitter、Facebookなど様々な認証方法が使用できます。
ここでは、申請がいらず手軽に利用できるGoogleアカウントによる認証を設定します。

https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/132608/34158432-c384-80ec-1c54-e48d658f7719.png

パッケージをインストール

firebaseパッケージをインストールします。

$ npm i -D firebase

Firebaseの設定ファイルを作成

Firebaseの設定ファイルを作成します。
使用する場所に直接記述してもいいのですが、それなりに長いので別ファイルに切り出します。

例:

firebase.config.js
export default {
  apiKey: 'AIzaSyDtYgrNF784HQeHA9fKdR9utHmD8OSerdY',
  authDomain: 'nuxt-firebase-authentication.firebaseapp.com',
  databaseURL: 'https://nuxt-firebase-authentication.firebaseio.com',
  projectId: 'nuxt-firebase-authentication',
  storageBucket: '',
  messagingSenderId: '570149189200',
  appId: '1:570149189200:web:ab17df9d6094c44e'
}

これらの値は、プロジェクトの設定画面から確認できます。

https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/132608/63bac64a-5249-2685-cc3f-06294b030e92.png

APIキーなど一見公開しないほうがよさそうなものも含まれていますが、登録したドメイン以外からは使用できないようになっているので問題ありません。1

Firebaseの初期化用モジュールを作成

Firebaseの初期化を行なうためのモジュールを作成します。
配置するディレクトリはどこでもいいのですが、僕はJavaScriptのモジュールはmodulesというディレクトリに配置することが多いです(Nuxt.jsの「モジュール」とは関係ありません)。

modules/firebase.js
import firebase from 'firebase/app'
import 'firebase/auth'
import config from '../firebase.config'

if (!firebase.apps.length) {
  firebase.initializeApp(config)
}

const auth = firebase.auth

export default firebase
export { auth }

!firebase.apps.lengthという条件のときのみfirebase.initializeApp(config)を実行しているのは、インスタンスが重複して生成されるのを防ぐためです。

ページを作成

Googleアカウントを使用してログイン・ログアウトをするだけのシンプルなページをつくってみましょう。

pages/index.vue
<template>
  <div v-if="isLoading">
    <span>Now loading...</span>
  </div>
  <div v-else>
    <div v-if="isSignedIn">
      <div>
        <span>You are signed in as {{ user.displayName }} ({{ user.email }}).</span>
      </div>
      <div>
        <button
          :disabled="isLoading"
          @click="signOut"
        >
          Sign out
        </button>
      </div>
    </div>
    <div v-else>
      <div>
        <span>You are not signed in.</span>
      </div>
      <div>
        <button
          :disabled="isLoading"
          @click="signIn"
        >
          Sign in with Google
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { auth } from '~/modules/firebase'

export default {
  asyncData () {
    return {
      isLoading: true,
      isSignedIn: false,
      user: {}
    }
  },
  mounted () {
    auth().onAuthStateChanged((user) => {
      this.isLoading = false
      if (user) {
        this.isSignedIn = true
        this.user = user
      } else {
        this.isSignedIn = false
        this.user = {}
      }
    })
  },
  methods: {
    signIn () {
      const provider = new auth.GoogleAuthProvider()
      auth().signInWithRedirect(provider)
    },
    signOut () {
      auth().signOut()
    }
  }
}
</script>

v-ifディレクティブで、ログイン状態によって表示する内容を切り替えています。
実際には、それぞれコンポーネント化したり、ルーティングで切り分けたりすべきでしょう。

ログインしていないとき

https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/132608/935630dd-e763-595a-bb2f-542882a4bdd7.png

ログインしているとき

https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/132608/4a21d3e4-363c-551e-c2db-cd62836fcc6d.png

Firebase Authenticationで承認済みドメインを追加

デフォルトでは、localhostとFirebaseのドメインのみが承認済みドメインに登録されています。
GitHub PagesやNetlifyなど、Firebase以外のサービスにデプロイする場合は、そのドメインを承認済みドメインに追加する必要があります。

https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/132608/0b84187d-dec2-20f3-4a3c-799bcde9bc03.png

参考リンク

10
12
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
10
12