【问题标题】:Laravel Sanctum Vue.js - How to check if session is expiredLaravel Sanctum Vue.js - 如何检查会话是否过期
【发布时间】:2021-04-05 03:36:02
【问题描述】:

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

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

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

感谢您的帮助!

【问题讨论】:

    标签: laravel vue.js authentication session


    【解决方案1】:

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

    把这个放在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)
      }
    )
    

    【讨论】:

      猜你喜欢
      • 2018-04-10
      • 2017-11-27
      • 1970-01-01
      • 2011-01-05
      • 2016-11-20
      • 2012-05-15
      • 2022-10-20
      • 2013-10-07
      • 2018-04-04
      相关资源
      最近更新 更多