简体   繁体   English

Laravel Sanctum Vue.js - 如何检查 session 是否已过期

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

I'm starting up a learning project with Laravel, VueJS.我正在使用 Laravel、VueJS 启动一个学习项目。 I'm using Sanctum cookie based.我正在使用基于 Sanctum cookie。 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.我已经在几个教程的帮助下进行了身份验证,但是没有一个教程涵盖了检查您的 session 是否过期的部分。 The tutorials that where covering it where using LocalStorage, and what I red about is that you should avoid LocalStorage.使用 LocalStorage 的教程,以及我所关注的是你应该避免使用 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.我正在寻找一种简单的可能性来检查用户是否仍然经过身份验证,如果没有,则将他们重定向到登录页面,或者更好的是,显示登录模式,并进一步显示 go 。

22 jan 2021 Still haven't got he answer:( 2021 年 1 月 22 日仍然没有得到他的答案:(

I'm fairly new to VueJS, Vuex and so on:)我对 VueJS、Vuex 等还很陌生:)

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把它放在App.vue创建的方法中

// 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)
  }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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