Vue.js + Firebase + GitHub認証
JS-proを始めて1週間のVue.js初心者です。
今回は、タイトルにあるように「Vue.js + Firebase + GitHub認証」WEBアプリを実装していきます。
開発環境は、Ubuntu18.04LTS です。
流れは以下の通りです。
さあ、やっていきましょう。
Vue のプロジェクトを作成
npm install -g @vue/cli
vue create github-auth
⚠ここでは、アプリ名をgithub-authにしています。cd github-auth/
npm run serve
ブラウザからlocalhost:8080
にアクセスして、この画面が出てくれば成功
Firebaseのプロジェクトを作成
- Firebase コンソールに移動
- プロジェクトを作成
- ウェブアプリを追加
FirebaseとGithubを連携
Authentication
赤線のURLをコピーしておくアプリを登録する
Application name : my-github-auth(アプリ名)
Homepage URL : ペーストし、末尾が.firebaseapp.com/
になるようにする
Authorization callback URL : ペーストする
クライアントIDとクライアントシークレットをFirebase側に貼り付け
赤部分GitHubが有効になれば成功
Vue のソースコードをいい感じに
Firebaseプロジェクトの設定を開く
Firebase側の情報をコピー
src/main.js
に貼り付け
import firebase from 'firebase' import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false // Your web app's Firebase configuration var firebaseConfig = { apiKey: "見せられないよ", authDomain: "github-auth-6d6da.firebaseapp.com", databaseURL: "https://github-auth-6d6da.firebaseio.com", projectId: "github-auth-6d6da", storageBucket: "github-auth-6d6da.appspot.com", messagingSenderId: "見せられないよ", appId: "見せられないよ" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); new Vue({ render: h => h(App), }).$mount('#app')
src/App.vue
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <GithubAuth msg="Welcome to Github-Auth"/> </div> </template> <script> import GithubAuth from './components/GithubAuth.vue' export default { name: 'App', components: { GithubAuth } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
src/components/GithubAuth.vue
<template> <div class="github-auth"> <h1>{{ msg }}</h1> <div v-if="user.uid" key="login"> <img :src="user.photoURL"/><br> [{{ user.displayName }}]<br> <button type="button" @click="doLogout">ログアウト</button> </div> <!-- 未ログイン時にはログインボタンを表示 --> <div v-else key="logout"> <button type="button" @click="doLogin">ログイン</button> </div> </div> </template> <script> import firebase from 'firebase' export default { name: 'GithubAuth', props: { msg: String }, data() { return { user: {} } }, created() { firebase.auth().onAuthStateChanged(user => { this.user = user ? user : {} }) }, methods: { doLogin() { console.log("doLogin"); const provider = new firebase.auth.GithubAuthProvider(); firebase.auth().signInWithPopup(provider) }, doLogout() { console.log("doLogout"); firebase.auth().signOut() } } } </script>
完成
npm install firebase
npm run serve
- ブラウザで
localhost:8080
にアクセス
参考文献
Vue.js+Firebaseで認証付きチャット | 基礎から学ぶ Vue.js
JavaScript による GitHub を使用した認証 | Firebase