DEV Community

ahmed elboshi
ahmed elboshi

Posted on

Building a Secure Vue.js Application - A Step-by-Step Guide with Nuxt.js, Vuetify.js, and Authentication

Introduction

Building a modern and secure web application involves combining powerful frameworks and libraries. In this guide, we'll walk through the process of setting up a Nuxt.js project with Vuetify.js for a stunning UI. Additionally, we'll implement a robust authentication and authorization system to ensure your application's security.

Step 1: Setting up Nuxt.js with Vuetify.js

  1. Create a New Nuxt.js Project:

    npx create-nuxt-app my-nuxt-app
    
  2. Choose Vuetify.js as UI Framework:

    During the setup process, choose Vuetify.js as your UI framework to leverage its pre-built components and styling.

  3. Install Additional Dependencies:

    cd my-nuxt-app
    npm install --save @nuxtjs/auth-next @nuxt/http @nuxtjs/axios
    
  4. Configure Vuetify.js:

    Open the nuxt.config.js file and add the Vuetify.js configuration under the buildModules section:

    export default {
      buildModules: ['@nuxtjs/vuetify'],
      vuetify: {
        // Customize Vuetify options here
      },
    }
    

Step 2: Setting up Authentication with Nuxt Auth

  1. Configure Nuxt Auth:

    Still in the nuxt.config.js file, add the authentication configuration under the auth section:

    export default {
      auth: {
        strategies: {
          local: {
            token: {
              property: 'token',
              required: true,
              type: 'Bearer',
            },
            user: {
              property: 'user',
            },
            endpoints: {
              login: { url: '/api/auth/login', method: 'post' },
              logout: { url: '/api/auth/logout', method: 'post' },
              user: { url: '/api/auth/user', method: 'get' },
            },
          },
        },
      },
    }
    

    Adjust the API endpoints based on your backend authentication setup.

  2. Create Login and Logout Pages:

    In the pages directory, create the following files:

    pages/login.vue

<template>
  <div>
    <h2>Login</h2>
    <form @submit.prevent="login">
      <label for="username">Username:</label>
      <input v-model="username" type="text" id="username" required>
      <label for="password">Password:</label>
      <input v-model="password" type="password" id="password" required>
      <button type="submit">Login</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    async login() {
      try {
        // Use the $auth.loginWith method to authenticate user
        await this.$auth.loginWith('local', {
          data: {
            username: this.username,
            password: this.password,
          },
        });

        // Redirect to the home page after successful login
        this.$router.push('/');
      } catch (error) {
        console.error('Login failed', error);
      }
    },
  },
};
</script>

Enter fullscreen mode Exit fullscreen mode

pages/logout.vue

<template>
  <div>
    <h2>Logout</h2>
    <button @click="logout">Logout</button>
  </div>
</template>

<script>
export default {
  methods: {
    async logout() {
      try {
        // Use the $auth.logout method to log the user out
        await this.$auth.logout();

        // Redirect to the login page after successful logout
        this.$router.push('/login');
      } catch (error) {
        console.error('Logout failed', error);
      }
    },
  },
};
</script>

Enter fullscreen mode Exit fullscreen mode
  1. Login Flow and Accessing User Model:
  • The login flow begins when the user submits the login form, triggering the login method in the login.vue component.
  • The this.$auth.loginWith method is used to send a request to the specified login endpoint (configured in nuxt.config.js) with the provided username and password.
  • Upon successful authentication, the user is redirected to the home page (/).
  • The user information, including the token and user model, is automatically stored in the Vuex store by Nuxt Auth.
  1. Accessing User Model:
  • To access the authenticated user's model from any component, you can use this.$auth.user or this.$store.state.auth.user.
  • This information is automatically updated by Nuxt Auth after successful login.
  1. Backend Integration:
  • The backend should handle authentication, validate user credentials, and return a token upon successful login.
  • The /api/auth/login endpoint is where you'd typically handle the authentication logic on the backend, validating the user's credentials and returning a token.
  • The /api/auth/user endpoint should return the user's information based on the provided token.

Feel free to customize these steps based on your specific backend and frontend requirements.

Top comments (0)