在 Laravel 中,在用戶保持不活動 x 分鐘后,會話過期并注銷。但是,在他重繪 頁面或轉到另一條路線之前,他仍然可以在應用程式中。
有沒有辦法讓他在會話過期后自動重定向到登錄頁面,而不需要重繪 頁面?
據我所知,我必須使用 Ajax 請求來完成,但我不確定如何。這是我搜索了一段時間后發現的:
$.ajax({
url:url,
type:"POST", // or get
data:parameters,
error: function(xhr, type, error){
window.location.replace("/login");
}
});
uj5u.com熱心網友回復:
當用戶登陸具有會話生命周期的頁面時,您可以啟動超時,并請求檢查用戶是否仍然登錄
// 4 hours
let sessionLifetime = 4 * 60 * 60;
setTimeout(() => {
// an authenticated endpoint, could be anything, if request fail, then user is not logged in anymore
axios.get('/me').catch(e => {
window.location.replace("/login");
})
}, sessionLifetime * 1000);
唯一的缺點是通過發出請求,您正在重繪 會話,因此如果請求通過,您只需要重新啟動 timeout :
// 4 hours
let sessionLifetime = 4 * 60 * 60;
let isAuth = () => {
// an authenticated endpoint, could be anything, if request fail, then
user is not logged in anymore
axios.get('/me').then(() => {
setTimeout(isAuth, sessionLifetime * 1000)
}).catch(e => {
window.location.replace("/login");
})
}
setTimeout(isAuth, sessionLifetime * 1000)
您可以創建一個專用于該檢查的端點,而不是使用隨機端點。我在這里使用了 axios,但它與 jquery $.ajax 的原理相同
另一種解決方案是假設在執行超時時用戶不再登錄,而不檢查請求,但這更有風險,因為用戶可以打開另一個選項卡
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/492849.html
