Home > Back-end >  Im getting 401 when i try to validate token, after a successfully login,
Im getting 401 when i try to validate token, after a successfully login,

Time:06-12

I'm working on a small project using VueJS and Vue Router and Laravel in the backend.

I tried too many times to use navigation guard but didn't succeed,

I have a login component works really fine, this is my login method : (as you can see I'm using localStorage for my token and some 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
      });

    }

my issue is with the navigation guard and exactly in beforeEach, I try to validate the token each time the user click on another page to check if the token is still alive or expired :

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' })
    });
 
});

and I have an axios client file that I use to send the header each time as you can see :

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;

the problem is : once I click on login I get my response like that : (which is correct, logged successfully )

Server Response (201), logged successfully

{
   data:{
     isLogged:true,
     token: gkljdfslkgjdfklgjfdlkgj,
     domain: http://user.multitenancy.test
   }
} 

then I get an error in validate-token I get 401, is like I'm not sending the token that I have saved in the localStorage as Bearer Authorization (check the interceptor please)

As you can see in my login method, token is saved in the localStorage, but im sending null in the Bearer Authorization, ( the problem only when I push login button to login ) and I see my localStorage data in the Devtools fine.

probably I should not verify the token in beforeEach ? What do you think the issue ?

CodePudding user response:

You need to get token from localStorage every time to get fresh data.

config.baseURL also need to set every time in your interceptor.

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 => {
    // get token from localStorage every time to get fresh data
    let userData = localStorage.getItem('token');

    let authenticated = {data:{}};
    
    if(userData !== null){
        authenticated = JSON.parse(userData);
        config.headers.Authorization = authenticated.data.token ? `Bearer ${authenticated.data.token}` : null;
        config.baseURL = ((authenticated.data.domain !== null) ? authenticated.data.domain : 'http://domain.test/api')
    }

    return config;

});

export default client;
  • Related