繁体   English   中英

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

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

我正在使用 Laravel、VueJS 启动一个学习项目。 我正在使用基于 Sanctum cookie。 我已经在几个教程的帮助下进行了身份验证,但是没有一个教程涵盖了检查您的 session 是否过期的部分。 使用 LocalStorage 的教程,以及我所关注的是你应该避免使用 LocalStorage。 我正在寻找一种简单的可能性来检查用户是否仍然经过身份验证,如果没有,则将他们重定向到登录页面,或者更好的是,显示登录模式,并进一步显示 go 。

2021 年 1 月 22 日仍然没有得到他的答案:(

我对 VueJS、Vuex 等还很陌生:)

谢谢您的帮助 !

试试这个,这是我迄今为止一直在使用的。 它不是很理想,但到目前为止效果很好,直到我能做得更好。

把它放在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