Vue + (Firebase + Google) === Easy Authentication

Vue + (Firebase + Google) === Easy Authentication

Hey learners!

I sometimes create youtube videos about things I'm working on, detailing how I did it - instead of a video, I'd like to share how you can use Firebase Auth to authenticate your users with Google!

Getting started, I'll assume that you probably already have a firebase project up and running, the only thing we need to do on the firebase console is active Google sign in:

Once that's done, we can get started on adding functionality to our view.

Here's a base template consisting of a button and the empty method googleSignIn

// @/views/SignUp.vue

<template>
  <div>
    <button @click="googleSignIn">
      Sign In with Google
    </button>
  </div>
</template>

<script>
import firebase from "firebase";
export default {
  name: "SignUp",
  methods: {
    googleSignIn: function() {
      // We'll create functionality here
    }
  },
};
</script>

Now that we have the basic structure in place, we can figure out what we need.

First, we need to create an instance of our preferred provider: let provider = new firebase.auth.GoogleAuthProvider();

Second, we decide what method we want to use - in our case we're going to use signInWithPopup()

Lastly, let's implement this into working code:

let provider = new firebase.auth.GoogleAuthProvider();
firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          let token = result.credential.accessToken;
          let user = result.user;
            console.log(token) // Token
            console.log(user) // User that was authenticated
        })
        .catch((err) => {
          console.log(err); // This will give you all the information needed to further debug any errors
        });

That's it! You can now authenticate users with Google in your firebase project - yay!

Note, if you don't know how to sign someone out, it's pretty easy:

firebase
        .auth()
        .signOut()
        .then(() => {
          alert("Successfully signed out.");
        });

Let me know if you have any questions about the process and happy coding 😊

 
Share this