🎉 New release for Pusher Chatkit - Webhooks! Extend your in-app chat functionality
Hide
Products
chatkit_full-logo

Extensible API for in-app chat

channels_full-logo

Build scalable realtime features

beams_full-logo

Programmatic push notifications

Developers

Docs

Read the docs to learn how to use our products

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Sign in
Sign up

Authentication in Vue using Vuex

  • Christian Nwamba
October 25th, 2018
You will need Node 8.9+ installed on your machine, and the Vue CLI 3.0. Some knowledge of Vue will be helpful.

Introduction

Authentication is one of the most important parts of any modern application, especially ones built with JavaScript. To successfully achieve this, there are numerous options available to developers when building web applications that involves protected routes.

The simplest option will be to set a unique token for each user in a localStorage. This means, whenever you need to access the user’s token or any other important user data for authentication purposes, we will need to fetch the token over and over again.

To handle this properly and ensure the we don’t have to reach out to the localStorage all the time, we need to persist the required data and easily access it whenever we want to. This will ensure that we have a centralized location for all our important data.

In this tutorial, we will be exploring the usage of Vuex to manage authentications within a Vue application.

Prerequisites

A knowledge of JavaScript and Vue is required for this tutorial. Also ensure that you have Node.js (version 8.9 or above) and Vue CLI 3.0 installed on your machine. If you have the previous versions of vue-cli installed globally already, kindly follow the installation guide here to upgrade to the latest version.

Setting up the application modules

Run the command below to begin the setup of our application:

    $ vue create vuex-auth-jwt

Choose the “manually select features” options and check the features we will need for this project by pressing space on your computer to select one. As shown below I have selected Babel, Router, Vuex and Linter / Formatter. You can skip this selection process and have them installed later but to get started easily, I will advise you select them:

For other instructions, type y to use history mode for router, this will ensure that history mode is enable within the router file that will automatically be generated for our project. In addition, select ESLint with error prevention only in order to pick a linter / formatter config. Next, select Lint on save for additional lint features and save your configuration in a dedicated config files for future projects. Type a name for your preset, I named mine vuerc:

Finally, hit enter to continue the installation process:

With this option, the Vue-CLI will automatically set up the store for Vuex and configure a file for router as well.

Install and configure Axios

We will need to perform HTTP requests within our application, for this, we will install axios. Open up the terminal and run the command below from your project directory:

    $ npm install axios --save

In addition, it is certain that we will be making use of axios across many of the components that will be created for our application, it will be preferable to import it once at the entry level and easily use it anywhere. Open the ./src/main.js file and update it with the content below:

    // ./src/main.js
    ...
      import Axios from 'axios'

      Vue.prototype.$http = Axios;
      const token = localStorage.getItem('token');
      if (token) {
        Vue.prototype.$http.defaults.headers.common['Authorization'] = token
      }

    ...

A major benefit of the setup above is that it makes it very easy for us to call axios directly inside any of our application’s components by simply using this.$http. We also proceeded to set up Authorization header with a token that will be sent with our requests if required.

Setting up the server for authentication

Next, we will set up a Node.js server for authentication. For this server, we will use SQLite as the database of choice for this tutorial. To install SQLite driver and other required dependencies for our server, run the command below:

    $ npm install --save sqlite3 bcryptjs jsonwebtoken body-parser

A quick look at some of the newly installed dependency:

Once the installation is completed, then it’s time for us to proceed and create the Node.js server that will handle user authentication as mentioned earlier. Within the root folder of your project directory, create a new folder named server and create a JavaScript file called app.js inside of it. This is where configuration takes place to import the required libraries to easily set up our server.

Now open the newly created file and add the following:

    // ./server/app.js

      "use strict";
      const express = require('express');
      const DB = require('./db');
      const config = require('./config');
      const bcrypt = require('bcryptjs');
      const jwt = require('jsonwebtoken');
      const bodyParser = require('body-parser');
      const db = new DB("sqlitedb")
      const app = express();
      const router = express.Router();
      router.use(bodyParser.urlencoded({ extended: false }));
      router.use(bodyParser.json());

      // CORS middleware
      const enableCrossDomain = function (req, res, next) {
          res.header('Access-Control-Allow-Origin', '*');
          res.header('Access-Control-Allow-Methods', '*');
          res.header('Access-Control-Allow-Headers', '*');
          next();
      }
      app.use(enableCrossDomain)

What we have done in the file above is to require all the necessary packages for our server to run effectively as stated initially. A close look at the file again, you will notice that we are also requiring a database file DB and configuration file config. We will create these files in a bit.

Lastly, we went further to set up a simple CORS middleware within a function named enableCrossDomain. This is to ensure that any cross origin resource errors are taken care of.

Define the authentication route

Next, we will define the route for registering a new user and also a login route to authenticate whenever the user comes back to log in. To begin, go back to the ./server/app.js file and include the code below immediately after the CORS middleware configuration:

    // ./server/app.js

    ...
      router.post('/register', function (req, res) {
          db.insert([
              req.body.name,
              req.body.email,
              bcrypt.hashSync(req.body.password, 8)
          ],
              function (err) {
                  if (err) return res.status(500).send("There was a problem registering the user.")
                  db.selectByEmail(req.body.email, (err, user) => {
                      if (err) return res.status(500).send("There was a problem getting user")
                      let token = jwt.sign({ id: user.id }, config.secret, {
                          expiresIn: 86400 // expires in 24 hours
                      });
                      res.status(200).send({ auth: true, token: token, user: user });
                  });
              });
      });

The content above is used to define the route for registering a new user. Here, we passed the request body to the insert method with our database class that will be created in the next section. We added a callback function to handle responses and provide accurate information of an authenticated user.

After successfully registering a user, we used email, since it will be configured as a unique field later in the tutorial to retrieve the user data and create an authentication token for the user by using the jwt packaged installed via npm earlier. We also used a secret key to verify a token sent to the server to uniquely identify a user. The configuration file for the secret key will be created soon.

Next, we will define the login route. Paste the content below within the app.js file right after the already configured /register route:

    // ./server/app.js 

      router.post('/login', (req, res) => {
          db.selectByEmail(req.body.email, (err, user) => {
              if (err) return res.status(500).send('Error on the server.');
              if (!user) return res.status(404).send('No user found.');
              let passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
              if (!passwordIsValid) return res.status(401).send({ auth: false, token: null });
              let token = jwt.sign({ id: user.id }, config.secret, {
                  expiresIn: 86400 // expires in 24 hours
              });
              res.status(200).send({ auth: true, token: token, user: user });
          });
      })

We basically received the request body containing the email and password of a user during the login process. We used bcrypt to easily compare the hashed password during registration with the supplied password and log the user in if there is a match, else we will throw an error.

Next, add the content below to complete the setting up process of the server:

    // ./server/app.js

    ... 
      app.use(router)
      let port = process.env.PORT || 3000;
      let server = app.listen(port, function () {
          console.log('Server listening on port ' + port)
      });

With the content above, our server will be available on port:3000. Now, we are done setting up our simple Node.js server.

Set up the database and config

Remember we made reference to a configuration and database file earlier? First, to set up the configuration file, create a new file in the same server directory and call it config.js. Add the following contents to it:

    // ./server/config.js

      module.exports = {
          'secret': 'applicationsecret'
      };

Finally, create another file for the database within the server directory called db.js and use the following content:

    // ./server/db.js

    "use strict";
    const sqlite3 = require('sqlite3').verbose();
    class Db {
        constructor(file) {
            this.db = new sqlite3.Database(file);
            this.createTable()
        }
        createTable() {
            const sql = `
                CREATE TABLE IF NOT EXISTS userAuth (
                    id integer PRIMARY KEY, 
                    name text, 
                    email text UNIQUE, 
                    password text)`
            return this.db.run(sql);
        }
        selectByEmail(email, callback) {
            return this.db.get(
                `SELECT * FROM userAuth WHERE email = ?`,
                [email], function (err, row) {
                    callback(err, row)
                })
        }
        insert(user, callback) {
            return this.db.run(
                'INSERT INTO userAuth (name,email,password) VALUES (?,?,?)',
                user, (err) => {
                    callback(err)
                })
        }
    }
    module.exports = Db

Here, we created a database class with methods like:

  • createTable(): to create a table named userAuth for the users
  • selectByEmail(): to fetch user’s data from the database
  • insert(): to insert user’s data into the database during the registration process

In case you missed any of the steps above, check here for the complete app.js file.

Set up components for the application

Now that we are done setting up the server, let’s create the required components for the application. First, locate the src/components folder and create a new folder named auth inside of it. This newly created folder will house both the Login and Register components.

The Login component

Create a new file Login.vue within the ./src/components/auth directory and add the content below:

     // ./src/components/auth/Login.vue

      <template>
       <div>
         <form class="login" @submit.prevent="login">
           <h1>Sign in</h1>
           <label>Email</label>
           <input required v-model="email" type="email" placeholder="Name"/>
           <label>Password</label>
           <input required v-model="password" type="password" placeholder="Password"/>
           <hr/>
           <button type="submit">Login</button>
         </form>
       </div>
      </template>
      <script>
      export default {
        data() {
          return {
            email: "",
            password: ""
          };
        },
        methods: {
          login: function() {
            let email = this.email;
            let password = this.password;
            this.$store
              .dispatch("login", { email, password })
              .then(() => this.$router.push("/"))
              .catch(err => console.log(err));
          }
        }
      };
      </script>

Here, in the <template> section we created the required fields to log in a user and within the <script>, we added the data attributes that will bind to the HTML form. Lastly, we included a method to handle the login process. We are using a Vuex action named login to handle this authentication. We will set this up later.

The Register component

Next, let’s create a component for registering users. To do this, create a new file Register.vue in the .src/components/auth folder and add the following to it:

    // ./src/components/auth/Register.vue

      <template>
        <div>
          <h4>Register</h4>
          <form @submit.prevent="register">
            <label for="name">Name</label>
            <div>
                <input id="name" type="text" v-model="name" required autofocus>
            </div>
            <label for="email" >E-Mail Address</label>
            <div>
                <input id="email" type="email" v-model="email" required>
            </div>
            <label for="password">Password</label>
            <div>
                <input id="password" type="password" v-model="password" required>
            </div>
            <label for="password-confirm">Confirm Password</label>
            <div>
                <input id="password-confirm" type="password" v-model="password_confirmation" required>
            </div>
            <div>
                <button type="submit">Register</button>
            </div>
          </form>
        </div>
      </template>
      <script>
      export default {
        data() {
          return {
            name: "",
            email: "",
            password: "",
            password_confirmation: "",
          };
        },
        methods: {
          register: function() {
            let data = {
              name: this.name,
              email: this.email,
              password: this.password,
            };
            this.$store
              .dispatch("register", data)
              .then(() => this.$router.push("/"))
              .catch(err => console.log(err));
          }
        }
      };
      </script>

Similar to the Login component, we created a form with the required fields to register a user and set up a method to handle the registration process within the <script> section. We also used a Vuex action named register.

The secure component

One of the main objectives of this application is to give a user access to a particular protected resource once they are authenticated. Let’s create this secured resource page.

To start, create a new folder named resources within the components folder and then create a new file called Resources.vue within it. Open Resources.vue and paste the content below in it:

    // ./src/components/resources/Resources.vue
    <template>
      <div>
        <h1>Protected resource page </h1>
      </div>
    </template>

Update the base component

Open ./src/App.vue file and update it with the content <template> below:

    // ./src/App.vue

    <template>
      <div id="app">
        <div id="nav">
          <router-link to="/">Home</router-link> |
          <router-link to="/about">About</router-link>
          <span v-if="isLoggedIn"> | <a @click="logout">Logout</a></span>
          <span v-else> | <router-link to="/login">Login</router-link></span>
        </div>
        <router-view/>
      </div>
    </template>

We included a Logout method to check if a user is logged in. Paste the code below after the <template> to include the logout() method:

    // ./src/App.vue

    <script>
    export default {
      computed: {
        isLoggedIn: function() {
          return this.$store.getters.isLoggedIn;
        }
      },
      methods: {
        logout: function() {
          this.$store.dispatch("logout").then(() => {
            this.$router.push("/login");
          });
        }
      }
    };
    </script>

Once a user clicks on the logout link, we dispatched a logout action to our vuex store and send the user to login page using this.$router.push('/login').

Building out the auth module

There are four things that go into a Vuex module: the initial state, getters, mutations and actions. We will set this up for our store. To begin, open store.js file and paste the code below in it:

    // ./src/store.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    import axios from 'axios'

    Vue.use(Vuex)
    export default new Vuex.Store({
      state: {
      status: '',
        token: localStorage.getItem('token') || '',
        user: {}
      },
      mutations: {
      },
      actions: {
      },
      getters: {
      }
    })

Here, we imported Vue, Vuex and axios and set the initial state for the authentication status, token and user information.

Set up Vuex actions

Our application is a minimal one and we only require to set up three different actions. They are login, register, and logout. Actions in Vuex provides us with a way of committing mutations to the vuex store. Go back to the store.js file and update the actions with:

     // ./src/store.js

      actions: {
          login({ commit }, user) {
            return new Promise((resolve, reject) => {
              commit('auth_request')
              axios({ url: 'http://localhost:3000/login', data: user, method: 'POST' })
                .then(resp => {
                  const token = resp.data.token
                  const user = resp.data.user
                  localStorage.setItem('token', token)
                  // Add the following line:
                  axios.defaults.headers.common['Authorization'] = token
                  commit('auth_success', token, user)
                  resolve(resp)
                })
                .catch(err => {
                  commit('auth_error')
                  localStorage.removeItem('token')
                  reject(err)
                })
            })
          },
          register({ commit }, user) {
            return new Promise((resolve, reject) => {
              commit('auth_request')
              axios({ url: 'http://localhost:3000/register', data: user, method: 'POST' })
                .then(resp => {
                  const token = resp.data.token
                  const user = resp.data.user
                  localStorage.setItem('token', token)
                  // Add the following line:
                  axios.defaults.headers.common['Authorization'] = token
                  commit('auth_success', token, user)
                  resolve(resp)
                })
                .catch(err => {
                  commit('auth_error', err)
                  localStorage.removeItem('token')
                  reject(err)
                })
            })
          },
          logout({ commit }) {
            return new Promise((resolve, reject) => {
              commit('logout')
              localStorage.removeItem('token')
              delete axios.defaults.headers.common['Authorization']
              resolve()
            })
          }
        }

Login action

The login action will be used to authenticate a user before logging in into the application and then commit the user’s credentials to the Vuex store.

Within this action object, we made a call to the server’s login route and return the necessary data. We then store the token in local storage and then pass the token and user data to auth_success to update the store’s attributes. Saving the token within the local storage instead of Vuex store will help to ensure that the user will still be logged in for as long as the token is still within the validity time.

Register action

Similar to the Login action, the will get the data of a user into our application and set a unique token in the local storage.

Logout action

After all the activity within our application, the user needs to be able to logout and have all the data created during the authenticated session destroyed. Once a user clicks on the logout link, we will remove the token we stored earlier.

Defining the mutations

Next, we will define mutators that will be used to change the state of data within the Vuex store. In the mutations object, add the following content:

    // ./src/store.js
          auth_request(state) {
            state.status = 'loading'
          },
          auth_success(state, token, user) {
            state.status = 'success'
            state.token = token
            state.user = user
          },
          auth_error(state) {
            state.status = 'error'
          },
          logout(state) {
            state.status = ''
            state.token = ''
          },

Create the getters

We will also add getters to get the value of the attributes of vuex state. Still within the ./src/store.js add the content below to the getters object:

    ./src/store.js

    isLoggedIn: state => !!state.token,
    authStatus: state => state.status,

Defining routes for authenticated and unauthenticated pages

As pointed out earlier, we intend to hide certain resources or pages from an unauthenticated user. For this, we will use vue-router to control the access of a user to a protected route. Once the user is authenticated we will give them access to a protected page and then redirect unauthenticated users back to the login page. Open the ./src/router.js file and import all the required component as shown below:

    // ./src/router.js

      import Vue from 'vue'
      import Router from 'vue-router'
      import store from './store.js'
      import Home from './views/Home.vue'
      import About from './views/About.vue'
      import Login from './components/auth/Login.vue'
      import Register from './components/auth/Register.vue'
      import Resource from './components/resources/Resources.vue'
      Vue.use(Router)
      let router = new Router({
        mode: 'history',
        routes: [
          {
            path: '/',
            name: 'home',
            component: Home
          },
          {
            path: '/login',
            name: 'login',
            component: Login
          },
          {
            path: '/register',
            name: 'register',
            component: Register
          },
          {
            path: '/resources',
            name: 'resources',
            component: Resource,
            meta: {
              requiresAuth: true
            }
          },
          {
            path: '/about',
            name: 'about',
            component: About,
          }
        ]
      })
      export default router 

We imported all the required components and then proceeded to define routes for the application. The only route requiring authentication here is the route that points to the page we want to protect. That is why we had to add a meta attribute to the route definition. If an unauthenticated user hits the /resources endpoint, he or she will be redirected back to the Login component. We will set up the requiresAuth meta in the next section.

Handling unauthorized access cases

To check for unauthorized access, add the code below within the router.js file just before the export default router:

    // ./src/router.js

    ...
    router.beforeEach((to, from, next) => {
      if (to.matched.some(record => record.meta.requiresAuth)) {
        if (store.getters.isLoggedIn) {
          next()
          return
        }
        next('/login')
      } else {
        next()
      }
    })
    ...

Running the application

Lastly, to test the application, run the command below to start the Vue application:

    $ npm run serve

This will start the development server for Vue on http://localhost:8080/, open that in your favorite browser to view the application.

And next, start the Node.js server in another terminal with:

    $ node server/app

This will print out a message to the console Server listening on port 3000;

Test the application

Now, if you navigate to the endpoint for our protected page http://localhost:8080/resources, you will be redirected to the login page as you have not been authenticated yet:

Proceed to the registration page http://localhost:8080/register and provide your details.

Once you are done, try to access the protected page again:

Conclusion

In this tutorial, we were able to learn how to use Vuex to manage authentication within our application. We were also able to set up a protected route that only authenticated users can have access to and redirect any unauthenticated user to a login page.

I hope you found this post helpful. Find the complete source code here on GitHub.

Clone the project repository
  • JavaScript
  • Node.js
  • Vue.js
  • no pusher tech

Products

  • Channels
  • Chatkit
  • Beams

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.