Categories
Vue

Adding Authentication to a Vue App with Firebase

Spread the love

Firebase provides us with built-in authentication capabilities.

We can manage users and authenticate them easily with it.

In this article, we’ll look at how to use Firebase’s auth capabilities in a Vue app.

Create Password-Based Accounts

We can create password-based accounts with a few lines of code.

To do this, we can write:

App.vue

<template>
  <div>
    <form @submit.prevent="createUser">
      <input type="text" v-model="email" placeholder="email">
      <input type="password" v-model="password" placeholder="password">
      <input type="submit" value="create user">
    </form>
  </div>
</template>
<script>
import firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  appId: "app-id"
};

export default {
  data() {
    return {
      email: "",
      password: ""
    };
  },
  beforeMount() {
    firebase.initializeApp(firebaseConfig);
  },
  methods: {
    createUser() {
      const { email, password } = this;
      firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then(() => alert("user creeated"))
        .catch(function(error) {
          console.log(error);
        });
    }
  }
};
</script>

We initialize Firebase with an object to configure it.

The apiKey has the API key.

authDomain is the URL of the Firebase app.

dataBaseURL has the URL to the database.

projectId has the Firebase project ID.

storageBucket is the URL of the storage bucket.

appId is the app’s ID.

In the template, we have the form that accepts an email and password.

And we have the createUser method to create the user.

The createUserWithEmailAndPassword method accepts an email and password string to create the user with the email and password.

The then callback is called when user creation is successful.

catch callback is called when user creation failed.

error has the code and message properties to get the source of the error.

Sign in a User with an Email Address and Password

We can sign in with a username and password with the signInWithEmailAndPassword method.

For example, we can write:

<template>
  <div>
    <form @submit.prevent="signIn">
      <input type="text" v-model="email" placeholder="email">
      <input type="password" v-model="password" placeholder="password">
      <input type="submit" value="sign in">
    </form>
  </div>
</template>
<script>
import firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  appId: "app-id"
};

export default {
  data() {
    return {
      email: "",
      password: ""
    };
  },
  beforeMount() {
    firebase.initializeApp(firebaseConfig);
  },
  methods: {
    signIn() {
      const { email, password } = this;
      firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then(() => alert("sign in successful"))
        .catch(error => {
          console.log(error);
        });
    }
  }
};
</script>

We added the signIn method which is mostly the same as the createUser method.

Sign in with Google

We can add sign in with Google.

First, we go to the Authentication section of our app.

Then we go to the Sign-in method section to add the domain that our app is hosted into the list of authorized domains.

Now we can add the authentication.

For example, we can write:

<template>
  <div>
    <button @click="signIn">sign in with google</button>
  </div>
</template>
<script>
import firebase from "firebase/app";
import "firebase/auth";
const provider = new firebase.auth.GoogleAuthProvider();
const firebaseConfig = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  appId: "app-id"
};

export default {
  data() {
    return {};
  },
  beforeMount() {
    firebase.initializeApp(firebaseConfig);
  },
  methods: {
    signIn() {
      firebase
        .auth()
        .signInWithPopup(provider)
        .then(result => {
          const token = result.credential.accessToken;
          const user = result.user;
          console.log(token, user);
        })
        .catch(error => {
          console.log(error);
          // ...
        });
    }
  }
};
</script>

We create the Google auth provider with the firebase.auth.GoogleAuthProvider constructor.

We added the signIn method which calls the signInWithPopup method with our auth provider object to add the sign-in functionality.

Then the then callback is called to get the user and token .

user has the user data.

token has the auth token.

The catch callback is called when there’s an error and it provides us with info about the error including the email, code, and message.

Conclusion

We can add authentication to our app easily with Firebase into a Vue app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *