I've been working on a small project utilizing VueJS, Vue Router, and Laravel for the backend.
Despite several attempts, I haven't been successful in implementing navigation guards.
My login component is functioning properly. Here's my login method (which utilizes localStorage for storing token and other data):
Login.vue
login() {
axios.post('http://proudata.test/api/login', this.user).then(response => {
if (response.data.data.isLogged == true) {
localStorage.setItem('token', JSON.stringify(response.data));
router.push({ name: 'dashboard' });
}
}).catch(error => {
this.error = true;
this.message = error.response.data.message
});
}
The issue arises with the navigation guard, specifically in beforeEach. My goal is to verify the token validity each time a user navigates to another page:
This is my routes.js file :
router.beforeEach(async (routeTo, routeFrom, next) => {
const authRequired = routeTo.matched.some((route) => route.meta.authRequired)
if (!authRequired) return next()
// **THE PROBLEM IS HERE IM GETTING 401 JUST AFTER LOGIN**
await client.get('validate-token').then(() => {
next();
}).catch(() => {
next({ name: 'login' })
});
});
In addition, I have a separate axios client file that handles headers:
Client.js
import axios from 'axios';
let userData = localStorage.getItem('token');
let authenticated = {data:{}};
if(userData !== null){
authenticated = JSON.parse(userData);
}
const client = axios.create({
baseURL: ((authenticated.data.domain !== null) ? authenticated.data.domain : 'http://domain.test/api')
});
client.interceptors.request.use(config => {
if(userData !== null){
config.headers.Authorization = authenticated.data.token ? `Bearer ${authenticated.data.token}` : null;
}
return config;
});
export default client;
After clicking the login button, I receive a response indicating successful login:
Server Response (201), logged successfully
{
data:{
isLogged:true,
token: gkljdfslkgjdfklgjfdlkgj,
domain: http://user.multitenancy.test
}
}
However, when attempting to validate the token, I encounter a 401 error suggesting that the token is not being sent as Bearer Authorization, despite being saved in localStorage. Any insights on why this may be happening?
Should I reconsider verifying the token in beforeEach? What could potentially be causing this issue?