Reputation: 179
I’m building an app with Adonis.js for the API and Vue.js for the front-end. I’m using JWT token to secure all routes of my API.
I understand the power of JWT to secure routes of API. When user create an account, a token is created to identified the user.
When I call my API from Vue I write the token of the active user in the header, and in my API I verify if the token is « active » and if is attributed on a user account ( and after that a make call to my databases..).
But the problem is (for me) I don’t understand how I can make a middleware to my vue route (verify if a user is authentify). I’have read some tutorial about that, and the conclusion is => store the token in local storage (ok, it’s logical) and make a middleware just checking if token exist.
But in my opinions this option is very not secure, because I can « enter » in my routes if I create a token manually in the local storage..
I’m very confusing about this concept.. can you open my eyes ehe ? Thanks
Upvotes: 1
Views: 1096
Reputation: 259
So yeah, you were right that you should be using Vuex to store the value for the token to retrieve it using getters
in your components/middleware. Your state
would look something like this:
export const state = () => ({
api_token: localStorage.getItem("api_token")
});
And getters
would look something like this:
export const getters = {
apiToken(state) {
return state.api_token;
}
}
To protect routes in the front-end you would be using router guard functions (https://router.vuejs.org/guide/advanced/navigation-guards.html). To give you an idea, this is what a simple check would look like:
router.beforeEach((to, from, next) => {
if (!store.getters["auth/apiToken"]) next('/login');
else next();
})
Good luck!
Upvotes: 3