Quick Summary

Security is a serious concern for every application and industry, particularly amidst data breaches, unauthorized access, and cyber fraud. Authentication and authorization have become indispensable elements for web applications to protect systems and information. In this blog, we have meticulously compiled a step-by-step tutorial for implementing Vue js authentication and authorization.

Table of Contents

Introduction

Will you accept a web application with no security or privacy?

You might not; in fact, no one would. After all, protecting and securing the confidentiality of the user and crucial data of the organization is crucial for any business.

According to CSO online survey, large organizations allocate an average of 11% of their IT budgets to security, while small businesses spend approximately 15%. This data clearly shows the significance of data security and privacy in the web application. Hence, numerous businesses adopt authentication and authorization for web apps and counter the increasing cyber threats efficiently.

The type of application is irrelevant. It can be a social media or e-commerce application, authentication and authorization is imperative to secure these apps. The increasing number of data breaches is a vital aspect that can be solved efficiently by implementing Vue js authentication and authorization.

This comprehensive guide will walk you through setting up authentication and authorization in your Vue.js application. Whether a seasoned Vue.js developer or a beginner, this tutorial will help you understand and implement these crucial aspects of web development. We will use Vue.js, Vue Router, and Vuex to build a simple example demonstrating these concepts.

What is Vue js Authentication and Authorization?

Authentication and authorization are pivotal aspects of any web application, playing a crucial role in preventing data breaches. In simple terms, these features ensure the safety and security of your web application.

Authentication validates user identity on your web application, while authorization controls user’s access based on their roles and permissions. In other words, authentication is a front-end function that handles user login, sign up, and log out. Whilst, authorization is the backend activity that empowers you to restrict permission.

Vue js, being an open-source frontend framework, simplifies implementation of security measures through its libraries, techniques, and tools. The Vue js makes the security journey a seamless experience with its tools like data binding, virtual DOM, state management, and robust router.

Prerequisites:

Before diving into this tutorial, ensure you have the following prerequisites in place:

  • You must be familiar with Vue.js fundamentals, such as ‘components’, ‘routes’, and ‘state management (Vuex)’ for creating authentication and authorization.
  • Vue CLI: Ensure you have Vue CLI installed globally. If not, you can install it by running’ npm install -g @vue/cli’.
Secure Your Future and Simplify Success With Bacancy

Hire Vue js developer from us to incorporate excellence in authorization and authentication; transform your app’s security for business success.

Step-by-Step Guide for Vue js Authentication and Authorization

The primary goal of this tutorial is to guide you through implementing authentication and authorization in a Vue.js application. By the end of this tutorial, you’ll clearly understand how to execute it in the Vue application.

However, first, you must adhere to the following requirements:
1. Set up a Vue.js project with Vue Router and Vuex
2. Create user authentication functionality using Vuex
3. Implement authentication guards to control route access based on user roles
4. Secure your Vue.js application and handle user authorization effectively

For Initial Setup, Follow These Steps:

Let’s begin by setting up a new Vue.js project. Follow these steps:
1. Create a new Vue.js project using Vue CLI:
a) Vue create auth-app

Copy Text
vue create auth-app

(note: ‘auth-app’ is application name, you can change it based on your preferences)
2. Select manually select feature option
a) Choose Router and Vuex to add to our project setup
b) Choose Vue version 2.x.
c) Choose default for the rest of the initial setup.

In the authentication process, users begin by logging in through the login screen. Upon successful authentication, they are redirected to the dashboard page. User data and tokens are stored in the Vuex store, and route access is controlled based on the authentication status.
We’ll start this process by creating ‘The Login.vue’ component.

Step 1: Create "TheLogin" component for TheLogin.Vue

In the TheLogin.vue file, we have designed a standard login form that includes email and password. Moreover, we have implemented HTML, CSS, and Laravel UPI to provide secure authentication.

While clicking the login button, the ‘userLogin ()’ function is triggered. This function validates the provided email and password with the backend API. If the credentials are correct, the backend sends a token and the user’s data, which we store in Vuex for future use.

Copy Text
<template>
  <form>
    <h2>Login Page</h2>
    <div class="imgcontainer">
      <img
        src="https://cdn.icon-icons.com/icons2/2468/PNG/512/user_kids_avatar_user_profile_icon_149314.png"
        alt="Avatar"
        class="avatar"
      />
    </div>

    <div class="container">
      <label for="email">Email</label>
      <input
        type="email"
        v-model="userData.email"
        placeholder="abc@gmail.com"
        required
      />

      <label for="passcode">Password</label>
      <input
        type="password"
        v-model="userData.passcode"
        placeholder="please enter your password"
        required
      />

      <button type="submit" @click.prevent="userLogin()">Login</button>
    </div>
  </form>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      userData: { passcode: "", email: "" },
    };
  },
  methods: {
    userLogin() {
      axios
        .post("http://localhost:8000/api/login", this.userData) //you can use alternate API for the authentication purpose
        .then((res) => {
          this.$store.commit("SET_AUTH", true);
          this.$store.commit("SET_TOKEN", res.data.token);
          this.$store.commit("SET_USER", res.data.employee);
          this.$router.push("/dashboard");
        });
    },
  },
};
</script>

<style scoped>
body {
  font-family: Arial, Helvetica, sans-serif;
}
form {
  border: 3px solid #fff;
}

h2 {
  text-align: center;
}
input[type="email"],
input[type="password"] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 2px solid #ccc;
  box-sizing: border-box;
}

button {
  background-color: #1d71be;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}

button:hover {
  opacity: 0.8;
}

.img container {
  text-align: center;
}

img.avatar {
  width: 10%;
  border-radius: 50%;
}

.container {
  padding: 50px;
}

@media screen and (max-width: 300px) {
  span.psw {
    display: block;
    float: none;
  }
  .cancel btn {
    width: 100%;
  }
}
</style>

Note: We have used Laravel API to check if the user exists in the backend database. If they do, it responds with a status code of 200 and provides us with that specific user’s token and user data. On the other hand, if the email address and password we entered are incorrect or not present in the database, we will receive an error message. Hence, you can use the alternate authentication API.

Step 2: Create Index file in the store directory (index.js)

In this Vuex store, we have stored the value of users after authentication, such as token, auth (representing authentication status), and user data. Inside getters provide access to these state properties. Mutations like ‘SET_TOKEN’, ‘SET_AUTH’, and ‘SET_USER’ modify the state, ensuring data consistency. Additionally, there’s an action called ‘resetState’ that allows users to reset all the states when the user logs out.

Copy Text
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    token: null,
    auth: false,
    user: {},
  },
  getters: {
    user: (state) => state.user,
    auth: (state) => state.auth,
    token: (state) => state.token,
  },
  mutations: {
    SET_TOKEN(state, payload) {
      state.token = payload;
    },
    SET_AUTH(state, value) {
      state.auth = value;
    },
    SET_USER(state, payload) {
      state.user = payload;
    },
  },
  actions: {
    resetUser({ commit }) {
      commit("SET_TOKEN", null);
      commit("SET_USER", {});
      commit("SET_AUTH", false);
    },
  },

});
export default store;

Step 3: Create The Dashboard component (TheDashboard.vue)

Later, in the ‘TheDashboard.vue’ file, we have displayed user details retrieved from the Vuex store. This component is accessible only when a user is authenticated.

If someone tries to access the dashboard directly without authentication, it will redirect to the login page, and the logic for this redirection to the login page is implemented in the ‘router.js file’. There is also a logout button which is used to reset the state from Vuex and redirect to the login page.

Copy Text
<template>
  <div class="user-details">
    <h2>User Details</h2>
    <ul>
      <li><strong>First Name:</strong> {{ user.first_name }}</li>
      <li><strong>Email:</strong> {{ user.email }}</li>
      <li><strong>Phone:</strong> {{ user.phone }}</li>
      <li><strong>Role:</strong> {{ user.role }}</li>
    </ul>
    <button v-if="user.role === 'Admin'" class="admin-button">
      Go to Admin Panel
    </button>
    <button class="logout-button" @click.prevent="logoutUser()">Logout</button>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    logoutUser() {
      this.$store.dispatch("resetUser");
      this.$router.push("/");
    },
  },
};
</script>
<style scoped>
.user-details {
  background-color: #f4f4f4;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
}
h2 {
  font-size: 24px;
  margin-bottom: 10px;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  font-size: 18px;
  margin-bottom: 5px;
}
button.admin-button {
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 3px;
  padding: 10px 20px;
  font-size: 18px;
  cursor: pointer;
  margin: 10px;
}
button.admin-button:hover {
  background-color: #0056b3;
}
button.logout-button {
  background-color: #ff0000;
  color: #fff;
  border: none;
  border-radius: 3px;
  padding: 10px 20px;
  font-size: 18px;
  cursor: pointer;
}
button.logout-button:hover {
  background-color: #a52a2a;
}
</style>

Step 4: Create Index file for the router (Index.js)

The last way to develop secure Vue js authentication and authorization is through the router. In this router configuration, two routes are defined: the default path ‘/’ mapped to the TheLogin component and the ‘dashboard’ path mapped to the TheDashboard component. An authentication guard is implemented to restrict access to the dashboard route for unauthenticated users.

The guard checks the authentication status and user data retrieved from Vuex. If authenticated, users can access the dashboard; otherwise, they will be redirected to the default path. This code effectively manages route navigation and access control based on authentication status.

Copy Text
import Vue from 'vue'
import store from "../store/index"
import VueRouter from 'vue-router'
import TheLogin from '../components/TheLogin'

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    name: 'home',
    component: TheLogin,
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('../components/TheDashboard.vue'),
  }
]
const router = new VueRouter({
  routes,
  mode: 'history',
})

router.beforeEach((to, from, next) => {
  const auth = store.getters["auth"];
  const user = store.getters["user"];
  if (auth && user) {
    next();
  } else if (to.path !== '/') {
    next('/');
  } else {
    next();
  }
});
export default router

With this, we conclude this tutorial. You may find the entire tutorial on our GitHub repository.

Also, let’s look at the final results of Vue js authentication and authorization

How Bacancy Can Help You With Vue.js Authentication and Authorization

Following the right steps, you can successfully implement authentication and authorization in a Vue.js application. This simple example demonstrates the fundamental concepts of user authentication and protecting routes based on user authorization. You can build upon this foundation to create more complex authentication systems in your Vue.js projects.

Securing your Vue.js authentication and authorization processes is crucial for your web application. Collaborate with an experienced Vue js development company like Bacancy to enhance and streamline your secure Vue.js authentication and authorization process, tailored to your business requirements.

Frequently Asked Questions (FAQs)

Yes, Vue.js is a versatile framework and can be integrated with multiple authentication methods like token-based authentication (JWT) and traditional session-based authentication.

Yes, Vue.js offers a robust ecosystem that allows your developers to implement authentication and authorization effectively. Due to its flexibility and integration capabilities, Vue js is quite suitable for developing secure web applications.

It is essential for Vue js applications to contain authentication for verification, identifying users, and ensuring only authorized users can access protected data. Moreover, it protects your data and maintains the high integrity of your Vue js application.

Don’t Take Risk and Secure Your Vue js App From Us!

Let Our Professionals Help You Tailor Solutions that Protect Your Vue Application and Ensure to Secure Your Success With Vue js Authentication and Authorization.

Contact us

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?