Web

Simple Authentication components strategy with Vue.Js

by Antonin Savoie 8 September 2018

A lot of application are using authentication, and we use many variants to handle it properly. The component system of VueJs is powerful, so let’s use it to simply handle authentication process.

It’s not always necessary to have a complex authentication system, a lot of applications has a simple need !

Note : the code sample shown in this article will use vue-cli and vue-router. The code is available here : https://github.com/Erilan/auth-components-strategy-vuejs

We can restrict page access with navigation guards in vue-router, but sometime the need is really simple, and we can use only components to handle page accessing.

A restricted page

Let’s say we have a page we want to protect, like a administration dashboard, an account page, or other things : a private page.

This page is really simple, but can make some api calls to display private information.

Now, let’s configure the vue-router to expose this page.


If you go to the page http://localhost:8080/#/private-page, you will see the private content.

private page

 

The login page

We now have the restricted page, we want a login page. For our example, we are going to use a very simple login page.


The login method is really simple : it just sends an event to the parent, but in real life cases, we have to make an api call, or check a cookie, or a vuex store… whatever will work.

Authentication component strategy

And now, here is the authentication component strategy :

Instead of having navigation guards, a redirection, or multiple components for each state of our user, we simply check if the user is logged in or not.

If the user is logged in, we display the page corresponding to the route, if not, we display the login component.

In our example, when user logs in, the component App.vue knows that the user is logged in, and display the router-view, not the login page.

The system is really simple in this example, but instead of looking for the isLoggedIn data, we can read a cookie, look in a vuex store, make a api call, etc…

We can also improve this to have not restricted route, by using nested routes.

And we can use Vue transition for a smoother switch between the login form and the restricted page

This solution is not the best, as it can’t handle all the cases, but for simple needs, it does the job !

Code can be found here : https://github.com/Erilan/auth-components-strategy-vuejs

 

Antonin Savoie

Antonin Savoie

Lead Développeur Web

Lead Web Developer at Kaliop and passionate about the Web, I work on a wide range of technologies such as Symfony, Vue.js, Serverless, AWS, Node.js, Docker, Varnish.

Comments

Add a comment

Your comment will be moderated by our administrators

Have a project? Our teams are here to answer your questions

Contact us