Protecting Your Users’ Data: A Comprehensive Guide to Firebase Authentication with Vue
Introduction to Firebase Authentication
When building an application, two crucial factors to consider are privacy and security. As cybercriminals become more sophisticated, authentication plays a vital role in deterring hacking and safeguarding your users’ sensitive information. Firebase Authentication provides a robust backend service to authenticate users in your application, supporting various authentication methods, including passwords, phone numbers, and identity providers like Google, Twitter, and Facebook.
Getting Started with Firebase Authentication
To integrate Firebase Authentication into your application, you can either use the Firebase UI, which handles the UI flows for signing users in with different providers, or manually set up the Firebase SDK in your project and configure support for your preferred provider. In this tutorial, we’ll take the manual route, creating the necessary views for user registration and sign-in, and providing support for email and password authentication.
Setting Up Your Vue Project
First, let’s create a new Vue project using the Vue CLI v3.0. If you have an older version of the CLI installed, uninstall it and then install the new CLI globally. Next, create a new Vue project and select the Default ([Vue 3] babel, eslint) preset, which will scaffold a new Vue application in the specified location.
npm uninstall -g @vue/cli
npm install -g @vue/[email protected]
vue create my-vue-app
cd my-vue-app
vue add router
vue add vuex
Configuring Your Firebase Project
To begin using Firebase, you’ll need a Gmail account. Head over to the Firebase console and create a new project. Firebase provides support for authentication using different methods, including social auth, phone numbers, and standard email and password. In this tutorial, we’ll focus on the email and password authentication method. Enable it for your project, as it’s disabled by default.
Registering Your Application
Under the authentication section for your project, click the sign-in method, and you should see a list of providers Firebase currently supports. Next, click the edit icon on the Email/Password provider and switch the Enable toggle on. Then, register your application under your Firebase project, and take note of the firebaseConfig object, which we’ll use shortly in our Vue application.
Installing Dependencies
Next, install the required dependencies, including Firebase, Vue Router, and Vuex. Firebase is the npm package we’ll use to interact with Firebase, Vue Router is the official router for Vue, and Vuex is a state management library for Vue.
npm install firebase vue-router vuex
Integrating Firebase with Vue
Now, let’s set up Firebase with our Vue project. In the main.js file, import the Firebase package and configure it to use the application credentials we noted from the Firebase console earlier. Create a file called firebaseConfig.js in the src folder, and add the application credentials.
// src/firebaseConfig.js
export default {
apiKey: '',
authDomain: '',
projectId: '',
};
// main.js
import { initializeApp } from 'firebase/app';
import firebaseConfig from './firebaseConfig';
initializeApp(firebaseConfig);
Creating Components
Create the required components for our project, including Register.vue, Login.vue, Dashboard.vue, and Navbar.vue. These components will handle user registration, login, dashboard display, and navigation, respectively.
Adding Routing to the Project
Before we begin working on our components, let’s add the routes that our application will have. Create a routes folder inside the src directory, and add an index.js file with the route configuration. Next, replace the content of the App.vue file with the router-view tag.
// src/routes/index.js
import { createRouter } from 'vue-router';
import Register from '../views/Register.vue';
import Login from '../views/Login.vue';
import Dashboard from '../views/Dashboard.vue';
const router = createRouter({
history: true,
routes: [
{ path: '/register', component: Register },
{ path: '/login', component: Login },
{ path: '/dashboard', component: Dashboard },
],
});
export default router;
<template>
<router-view></router-view>
</template>
Managing State with Vuex
Vuex is a state management library that provides a centralized store to help manage the components in your Vue application. Create a store.js file in the src directory, and define the state, getters, mutations, and actions for our authentication system.
// src/store.js
import { createStore } from 'vuex';
const store = createStore({
state: {
authenticated: false,
user: null,
},
getters: {
isAuthenticated(state) {
return state.authenticated;
},
getUser(state) {
return state.user;
},
},
mutations: {
setAuthenticated(state, authenticated) {
state.authenticated = authenticated;
},
setUser(state, user) {
state.user = user;
},
},
actions: {
async login({ commit }, { email, password }) {
// login logic here
},
async register({ commit }, { email, password }) {
// register logic here
},
async logout({ commit }) {
// logout logic here
},
},
});
export default store;
Registering Users
Let’s see how we can register users and store their details on Firebase. Edit the Register.vue component, and add the necessary code to handle user registration. When the form is submitted, the Register function is called, which handles the actual registration of the user on Firebase.
<template>
<form @submit.prevent="register">
<input type="email" v-model="email" />
<input type="password" v-model="password" />
<button type="submit">Register</button>
</form>
</template>
<script>
export default {
data() {
return {
email: '',
password: '',
};
},
methods: {
async register() {
try {
const userCredential = await firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password);
// handle user registration success
} catch (error) {
// handle user registration error
}
},
},
};
</script>
Logging in Users
Next, let’s learn how we can allow a user to log in. Edit the Login.vue component, and add the necessary code to handle user login. The Login.vue component is similar to the Register.vue component.
<template>
<form @submit.prevent="login">
<input type="email" v-model="email" />
<input type="password" v-model="password" />
<button type="submit">Login</button>
</form>
</template>
<script>
export default {
data() {
return {
email: '',
password: '',
};
},
methods: {
async login() {
try {
const userCredential = await firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password);
// handle user login success
} catch (error) {
// handle user login error
}
},
},
};
</script>
Creating the Dashboard Component
Define a simple dashboard view with a bootstrap alert that informs the user that they’ve successfully logged in, displays the user’s profile, and shows the log out button. Add the necessary code to the Dashboard.vue file.
<template>
<div>
<div class="alert alert-success" role="alert">
You have successfully logged in!
</div>
<p>Welcome, {{ user.displayName }}!</p>
<button @click="signOut">Log out</button>
</div>
</template>
<script>
export default {
computed: {
user() {
return this.$store.getters.getUser;
},
},
methods: {
async signOut() {
try {
await firebase.auth().signOut();
this.$store.dispatch('logout');
this.$router.push('/login');
} catch (error) {
// handle logout error
}
},
},
};
</script>