简体   繁体   中英

Laravel Sanctum Vue.js - How to check if session is expired

I'm starting up a learning project with Laravel, VueJS. I'm using Sanctum cookie based. I have got the authentication working with the help of several tutorials, but none of the tutorials covers the piece of checking if your session is expired or not. The tutorials that where covering it where using LocalStorage, and what I red about is that you should avoid LocalStorage. I'm looking for a simple possibility to check if a user is still authenticated and if not, then redirect them to the login page, or even better, show a modal to login and go further where they are.

22 jan 2021 Still haven't got he answer:(

I'm fairly new to VueJS, Vuex and so on:)

Thanks for the help !

Try this, its what I've been using so far. Its not very ideal but works out fine so far until I can make it better.

Put this in App.vue created method

// each call needs csrf token to work, so we call this on app load once.
axios.get(axios.rootURL + '/sanctum/csrf-cookie').catch(() => {
  alert('Something went wrong, Contact admin <br> ErrorCode: csrf')
})

// this part is not necessary, you may adapt as required
// let isLoggedIn = localStorage.getItem('isLoggedIn') ? true : false
// this.setIsLoggedIn(isLoggedIn)

axios.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// this is the actual part you need, here we check on each call
// if we get error 401 which is unauthenticated we redirect to login. That's it
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response.status === 401) {
      this.$router.push({ name: 'login' })
      localStorage.removeItem('isLoggedIn')
      this.setIsLoggedIn(false)
    }

    return Promise.reject(error)
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM