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
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
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
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!