Create Your Own Vue Application: Authentication with Firebase
Tags: vue, firebase, beginners, tutorial
Published: 2022-10-06 02:41:29

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](https://firebase.google.com/docs/auth/android/firebaseui) 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/](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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxxxtl90imv3kfx39med.png)


## Vue Project

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

```bash
vue create firbase-auth
```
Next,install the dependency.

```bash
cd firbase-auth
npm install firebase
```

## Firebase Config

Init firebase SDK.

```bash
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;
```

Create a new Component
```bash
<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>
```

Config the router:

```bash
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
```

Then run

```bash
npm run serve
```

## **Advanced usage**

Now I want every one can access home page, the page “/about” are only open for logged users.[Nprogress](https://ricostacruz.com/nprogress/) is a nanoscopic progress bar and I import the dependency.

```bash
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();
});
```
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;
```

Then import permission.js

```bash
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')
```
Then run the project.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6eso43aqfrdy1thorv3x.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3lwdkafay9ulemepkhp.png)
I choose "signIn with Github".After a successful login, I am able to access the about page.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8k0udamtvlvijm0p61m.png)





## 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](https://github.com/zhng1456/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](https://dev.to/zhng1456/easy-way-to-separate-java-backend-and-vue-frontend-3f5n). Finally, thanks for reading.

<a href="https://www.buymeacoffee.com/zhng1456" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>