Handling Authentication in Vue with Vuex

Image for post
Image for post
https://vuejs.org/

Frontend development is a major part of the web and has grown rapidly in the past years. With the growing build tools and many javascript frameworks it has grown much complex. Business organization are focusing more on front-end development to enhance user interaction, site efficiency, interactivity and look & feel.

The development of JavaScript, especially in the last year. 2018 was a year with a lot of action, changes and new initiatives in front-end web development. The choice to become the preferred JavaScript framework has heated up, as more projects have started to choose to React js including Vue over Angular followed by other frameworks till today.

I personally preferred Vue because of following strong points:

  1. Simplicity
  2. Modularity
  3. Scalebility
  4. Flexibility
  5. Light Weight
  6. Maturity of the framework

Presently it has 125,083 Github stars and left many other top front-end development tools behind. It was first released in 2013. In last 4–5 years, the progress is significant with its active contributors and supporters.

In this tutorial we will learn how to store the token locally into your machine and place router guards to prevent unauthorized access into the routes for new user login and registering a valid user into our database. Finally we will move on to destroying the token during logout.

Setting Up:

Now let’s dive in authenticating a vue application with Vue-router, Vuex and Axios. I presume you have Vue CLI 3 installed and other required setup made. Firstly, we will scaffold our application with our CLI command.

Image for post
Image for post

Here we have created a new project with the name vue-auth. I have included vue-router, vuex and axios for our HTTP requests. We have also used Tailwind CSS for our CSS framework. Tailwind is written in PostCSS and configured in JavaScript, which is meant us to have the full power of a real programming language.

Now, we have made some necessary changes and the screen looks like this for now.

Image for post
Image for post

Here what have we done so far is we have setup our routes into two separate views. We have styled a bit with Tailwind. Now lets look at the piece of code:

Our Login:

We will create a login.vue file where we will write following code:

Image for post
Image for post
src/views/Login.vue

In the code above we have our input fields with v-model directive which holds the value of the respective input holders. And we will have our values holding will be returned below in script tags.

Image for post
Image for post
src/views/Login.vue

After the above code we will take up our store and do some necessary changes getting and storing the token locally inside the browser.

Image for post
Image for post
src/store.js

In the code above we have stored our token into our local storage which we received from our backend into the token value. We have also checked whether the user is logged in or not. The data received from the model are posted through our API endpoint using axios. Further we have to dispatch the getToken method we made, take a look at the following code.

Image for post
Image for post
src/views/Login.vue

Here we have chained multiple call with then() to our loginAction function which will eventually lead us to next desired route. We have our all code working fine now the problem that we have is we can get into any route now we have to place some router guards to our routes which we will place it into our main main.js file and add up some meta data to our router.js file.

Image for post
Image for post
main.js,router.js

We have added a new route to our router file named ourApp which we will push our route after the successful login completion. We have placed some meta field in our route handlers naming needsVisitors and needsAuth to the respective route fields. And also we have coded some router-guards along side the meta data received from our routes.

Our Register:

For our new user registration we are going to make some changes in our register.vue file which serves as a separate view for the application. Lets bind the input values and use our store to dispatch some action for the new user.

Image for post
Image for post
src/store.vue

Here we have form our validateBeforeSubmit function which will be called before the form input bindings have been submitted into the database with POST method. We also have installed vee-validate imported in main.js as our development dependencies which will check if any false input in the fields.

After the register action it will call store to dispatch action with userRegister. In the store.js we have our our action made which looks like below:

Image for post
Image for post
src/store.vue

Along with the valid data in our vue model we have our three data fields posted into the database with POST method. Now the next step is to destroy the token we have stored locally.

Clearing User:

Image for post
Image for post
ourApp.vue — Logout.vue — store.js

Lets first create our logout button in the ourApp.vue and we will redirect into the Logout.vue, where we will dispatch destroyToken from the store. In the store we have the the function name which we will have headers of our authentication and post it into the database. We will check whether the state token is null or not and proceed with the function.

Finally, we will remove the token stored in our localstorage during the logout. Tokens are pure JavaScript object. If we building a single page site, using something like local storage means your web pages can run independently of any web server. You need only the browser storage and there would be no need for storing any data in the server.

Also, the other great thing about local storage is the size restriction: we can use it to cache data for later usage. But in the case of cookies, this isn’t the case as there is a size restriction of 4KB, while Local storage provides at least 5MB of data storage across all major web browsers.

As JWT is a fairly new concept, one might not find the libraries in all the languages out there. Adding to it, neither JWT nor Sessions solve the CSRF or XSS issues, as it completely depends on how we send the data. JWT is fast for development is less customizable, risky and slightly complicated to understand.

But there is still debate whether Cookies or Token is better for storing the data. I personally prefer using token as it is much easier and widely loved by developers.

Thanks for reading. Happy Coding !!

Written by

Product Designer and Frontend Developer | https://twitter.com/ishan02016

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store