Remove token in frontend using Vue JS after deleting it from database in backend with Laravel?

595 Views Asked by At

I'm developing an application with Vue 3 and Laravel 9.

I did all login, registration and logout. However, I had an idea to keep the session unique per browser. I delete all tokens on user login if they exist. That way I can have front-end control with just one session open per browser, as I've already done this logic there.

The problem knowing the ways I can remove the token on the front-end to logout/redirect the user to login, after receiving the "Unauthenticated". For I check the vue routes with the token in localStorage.

Remembering, I'm using sanctum.

I'm looking for procedures. However, I'm afraid of doing something wrong, as I wonder about data security and vulnerabilities, as these processes of building a software require caution and a lot of testing.

1

There are 1 best solutions below

3
On

I'm not sure if i got the question right, but you would normalle use an axios interceptor like so:

_axios.interceptors.response.use(
  response => response,
  error => {
        
    if (error.response.status === 401) {
      console.log('Intercept: 401 - Unauthenticated')
      //DELETE THE TOKEN FROM STORAGE AND FROM AXIOS HEADER
      delete window.axios.defaults.headers.common.Authorization
      localStorage.removeItem('token')

      return router.replace({ name: 'login' })
    }
    if (error.response.status === 403) {
      console.log('Intercept: 403 - Unauthorized')
    }
    if (error.response.status === 422) {
      console.log('Intercept: 422 - Validation Error')
    }
        
    return Promise.reject(error)
  },
)