[英]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.