DEV Community

Cover image for Create Your Own Vue Application: Authentication with Firebase
Yw Zhang
Yw Zhang

Posted on

Create Your Own Vue Application: Authentication with Firebase

As a programmer,everyone wants to create magic app.The first step is to authenticate users to your application.Firebase authentication provides backend services to help authenticate users to your application. To integrate Firebase authentication to your application, you can use either the Firebase UI which handles the UI flows for signing in users using different providers or you can manually set up the Firebase SDK in your project and provide support for any provider you would like to use.

In this tutorial,We’ll integrate Firebase UI to a Vue,Vue router project.

Setting Up a Firebase Project

Sign in https://firebase.google.com/ and create a new project.Under the authentication tab for your project, click the sign-in method and you should see a list of providers Firebase currently supports.Next,enable Email/Password and Github.

Image description

Vue Project

Create the project and choose Vue2.x,Vue Router,Vuex.

vue create firbase-auth
Enter fullscreen mode Exit fullscreen mode

Next,install the dependency.

cd firbase-auth
npm install firebase
Enter fullscreen mode Exit fullscreen mode

Firebase Config

Init firebase SDK.

import firebase from 'firebase/compat/app';
import Cookies from "js-cookie";

const config = {
// get your project config from firebase console
}

firebase.initializeApp(config);

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    user.getIdToken().then(idToken => Cookies.set('access-token', idToken, { expires: 2 }));
  }
}, function(error) {
  console.log(error)
});

export const firebaseAuth = firebase.auth;
Enter fullscreen mode Exit fullscreen mode

Create a new Component

<template>
  <div>
    <div id='firebaseui-auth-container' v-if='!isLogin'>
    </div>
    <div v-else>
      <span>You already logged in</span>
      <button @click='handleSignOut'>SignOut</button>
    </div>
  </div>
</template>

<script>
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import * as firebaseui from 'firebaseui'
import 'firebaseui/dist/firebaseui.css'
import { firebaseAuth } from "@/conf/firebaseConfig";
import { Common } from "@/utils";
import Cookies from "js-cookie";

export default {
  data() {
    return {
      isLogin: Common.validString(Cookies.get('access-token'))
    }
  },
  mounted() {
    if (Common.validString(Cookies.get('access-token'))) {
      return;
    }
    const firebaseConfigUI = {
      signInSuccessUrl: 'http://localhost:8080',
      signInOptions: [
        firebaseAuth.GithubAuthProvider.PROVIDER_ID,
        firebaseAuth.EmailAuthProvider.PROVIDER_ID,
      ],
      tosUrl: '<your-tos-url>',
      // Privacy policy url/callback.
      privacyPolicyUrl: function () {
        window.location.assign('<your-privacy-policy-url>');
      }
    };
    const ui = firebaseui.auth.AuthUI.getInstance() || new firebaseui.auth.AuthUI(firebase.auth());
    ui.start('#firebaseui-auth-container', firebaseConfigUI);
  },
  methods: {
    handleSignOut() {
      firebaseAuth().signOut().then(() => {
        console.log('signOut success');
        Cookies.remove('access-token');
        Cookies.remove('urlBeforeSso');
        window.location.reload();
      }).catch((error) => {
        console.log(error);
      });

    }
  }
}
</script>

<style scoped>

</style>
Enter fullscreen mode Exit fullscreen mode

Config the router:

import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView'
import FirebaseUiLogIn from "@/components/FirebaseUILogIn";

Vue.use(VueRouter)

const routes = [
  { path: '/', name: 'home', component: HomeView },
  { path: '/about', name: 'about', component: AboutView },
  { path: '/signIn', name: 'signIn', component: FirebaseUiLogIn },
]

const router = new VueRouter({
  routes
})

export default router
Enter fullscreen mode Exit fullscreen mode

Then run

npm run serve
Enter fullscreen mode Exit fullscreen mode

Advanced usage

Now I want every one can access home page, the page “/about” are only open for logged users.Nprogress is a nanoscopic progress bar and I import the dependency.

import Cookies from 'js-cookie';
import { req, Common } from '@/utils';
import router from '@/router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

NProgress.configure({ showSpinner: false });

const isLogin = () => Common.validString(Cookies.get('access-token'));

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.path === '/signin') {
    if (isLogin()) {
      next({ path: '/' });
      NProgress.done();
    } else {
      next();
    }
    return;
  }

  if ((to.path === '/404' || to.path === '/') && isLogin()) {
    next();
    return;
  }

  if (isLogin()) {
    next();
  } else {
    req.redirectToSso();
    Cookies.set('urlBeforeSso', to.fullPath);
    next();
    NProgress.done();
  }
});

router.afterEach(() => {
  NProgress.done();
});
Enter fullscreen mode Exit fullscreen mode

this is the code of "req.redirectToSso"

import Cookies from 'js-cookie';
import axios from 'axios';
import { Notification } from 'element-ui';
import Common from "@/utils/common";

const req = {};

req.redirectToSso = () => {
    if (window.location.href.indexOf('#/signin') > -1) {
        return;
    }
    Cookies.set('urlBeforeSso', window.location.href);
    window.location.href = window.location.origin + window.location.pathname + '#/signin';
};

export default req;
Enter fullscreen mode Exit fullscreen mode

Then import permission.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import './permission'

Vue.use(ElementUI)
Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
Enter fullscreen mode Exit fullscreen mode

Then run the project.

Image description

Click about page and url redirects to "/signin".

Image description
I choose "signIn with Github".After a successful login, I am able to access the about page.

Image description

About me

I'm a programmer dedicated to sharing code and knowledge.Currently I'm working on the development of a recommender system, and I'm preparing to build a recommender system using firebase's related functions. So, in this post I try to write the login module.You can find the complete code in github recommend-system.

My next plan is to code the backend of the recommender system. The interaction between the backend and the frontend can refer to my previous article. Finally, thanks for reading.

Buy Me A Coffee

Top comments (0)