0
一旦創建了jwt訪問令牌,我就將它存儲在localstorage中,然後在任何地方使用它。在這裏,我面臨的問題,一旦jwt令牌過期,我無法搜索。所以我想要一旦jwt令牌失效,它應該自動創建。應該如何做到這一點。謝謝如何在過期後自動創建jwt令牌
一旦創建了jwt訪問令牌,我就將它存儲在localstorage中,然後在任何地方使用它。在這裏,我面臨的問題,一旦jwt令牌過期,我無法搜索。所以我想要一旦jwt令牌失效,它應該自動創建。應該如何做到這一點。謝謝如何在過期後自動創建jwt令牌
下面是一個可能的解決方案 - 一個簡單的redux中間件,它將刷新即將到期的現有未過期令牌。
它使用jwt-decode函數庫,並假定存在實際更新的renewToken
函數。
有關更多詳細信息,請參閱代碼中的註釋。
import jwtDecode from 'jwt-decode'
import { renewToken } from authManager
// If less than this time in seconds to expiry - renew the token
const EXPIRY_THRESHOLD = 600
// Milli seconds between expiry checks
// Should be longer than the time it takes for a request for new token to succeed/fail
// This is how we avoid multiple token requests
const CHECK_INTERVAL = 10000
// Timestamp of last time we checked the token for expiry
let lastCheckTs = -CHECK_INTERVAL
/**
* Get time in seconds until the id_token expires.
* A negative value means it has already expired (or doesn't exist)
*/
function getTimeToExpiry(key) {
let jwt = localStorage.getItem(key)
if(jwt) {
let jwtExp = jwtDecode(jwt).exp
let expiryDate = new Date(0)
expiryDate.setUTCSeconds(jwtExp)
return Math.floor((expiryDate.getTime() - Date.now())/1000)
}
return -1
}
export default store => next => action => {
const now = Date.now()
if (now - lastCheckTs < CHECK_INTERVAL) {
// We checked recently, just continue
return next(action)
}
lastCheckTs = now
const timeToExpire = getTimeToExpiry('id_token')
// This middleware is only concerned with keeping a valid session alive.
// If the existing token is stale or non-existent -
// do nothing and let other parts of the app take care of
// getting a completely new valid token (EG by prompting the user to login)
// If the existing token has a long time to expiry - do nothing until the next check
// However, if the existing token is valid but will expire soon - try to renew it.
if (timeToExpire > 0 && timeToExpire < EXPIRY_THRESHOLD) {
// Try to renew the token
const current_id_token = localStorage.getItem('id_token')
renewToken(current_id_token, function (err, result) {
if (err) {
// Do nothing -
// If we got here it means that the current token is still fresh,
// so we'll just try again in the next expiry check
} else {
// Store the new token
localStorage.setItem('id_token', result.id_token)
}
});
}
return next(action)
}
謝謝我會試試這種方式。 –
也許檢查每個用戶交互(EG行動派遣或路線改變)到期,如果到期時間太近,更新智威湯遜。這樣,如果用戶長時間沒有交互,令牌將會過期,這是可以接受的。 – Giladd
感謝您的回覆。實際上,如果訪問令牌已過期,我正在檢查動作創建者,但問題在於我正在對某個事件調用動作創建者。意味着我需要執行任何事件來檢查錯誤。我已經爲創建jwt令牌保留了獨立的動作創建器。我不能在另一個動作創建者中調用一個動作創建者。請引導我。 –