Using Vuex to store authentication in Local Storage

28th December 2018

I'm currently Rebuilding BiblioSpot as a standalone Vue app which fetches data from our private API. At the start of the project, I was wondering, how I should go about handling Authentication? I tried out a few different solutions but this one seems to work, so I'm going to go along with it.

The first thing I did was obviously create a new Vue app so I did vue create app-name. I chose Vue router, Vuex and some other stuff that was there that looked like a good option. I also installed Axios for the HTTP request stuff. Yes I know Vue has their own package for this and there is a similar function built into Javascript, but who cares.

Now, the first thing that we should do is to write code to allow the user to actually login. I'm using Laravel Passport for API auth and it gives us the /oauth/token route which we can send a payload to and it will give us our access token. A simple bit of code like this should do the jiffy.

Once you've got your HTTP requests to work, you can create your Vuex store. This is a simplified version of my store.js file.

Basically what I've done in my Vuex store is set it up so that you can change and view the bearer/access token.

Now that we've got this in place, when you login your token should be set in your Vuex store and you should be directed to /. (you can change this route in the success part of the Axios request in the Login.vue component)

However, if you refresh the page, your bearer token is no longer in the Vuex store. This is where local storage comes in. It can store data that can be used even if you close the browser entirely.

The way I stored my state in local storage was by using the vuex-persistedstate npm package. You just need to install it and import it into your store, like so.

Now you should be able to login and refresh your page and your bearer token will still be in your store.

Now you've pretty much got everything working. However, if you need to check within views/components of your application if the user is logged in or out for that matter I've devised a little component that you can use that will detect such things and will redirect the user to the login page. (If you need to check that the user is logged out you can place the redirect at the other side of the if statement)

That's us done!

Signup to my newsletter to get links to things I find cool on a regular basis.