javascript
jwt的token自动续约_JWT(JSON Web Token)自动延长到期时间
cchamberlain..
6
如果您使用的是節點(React/Redux/Universal JS),則可以安裝npm i -S jwt-autorefresh.
此庫根據用戶計算的訪問令牌到期之前的秒數(基于令牌中編碼的exp聲明)計劃刷新JWT令牌.它有一個廣泛的測試套件,可以檢查很多條件,以確保任何奇怪的活動都伴隨著有關環境配置錯誤的描述性消息.
完整的示例實現
import autorefresh from 'jwt-autorefresh'
/** Events in your app that are triggered when your user becomes authorized or deauthorized. */
import { onAuthorize, onDeauthorize } from './events'
/** Your refresh token mechanism, returning a promise that resolves to the new access tokenFunction (library does not care about your method of persisting tokens) */
const refresh = () => {
const init = { method: 'POST'
, headers: { 'Content-Type': `application/x-www-form-urlencoded` }
, body: `refresh_token=${localStorage.refresh_token}&grant_type=refresh_token`
}
return fetch('/oauth/token', init)
.then(res => res.json())
.then(({ token_type, access_token, expires_in, refresh_token }) => {
localStorage.access_token = access_token
localStorage.refresh_token = refresh_token
return access_token
})
}
/** You supply a leadSeconds number or function that generates a number of seconds that the refresh should occur prior to the access token expiring */
const leadSeconds = () => {
/** Generate random additional seconds (up to 30 in this case) to append to the lead time to ensure multiple clients dont schedule simultaneous refresh */
const jitter = Math.floor(Math.random() * 30)
/** Schedule autorefresh to occur 60 to 90 seconds prior to token expiration */
return 60 + jitter
}
let start = autorefresh({ refresh, leadSeconds })
let cancel = () => {}
onAuthorize(access_token => {
cancel()
cancel = start(access_token)
})
onDeauthorize(() => cancel())
免責聲明:我是維護者
是的,解碼是僅客戶端解碼,不應該知道這個秘密.該秘密用于對JWT令牌服務器端進行簽名,以驗證您的簽名是否最初用于生成JWT,并且永遠不應該從客戶端使用.JWT的神奇之處在于它的有效負載可以在客戶端進行解碼,并且內部聲明可用于構建您的UI而無需保密.唯一`jwt-autorefresh`解碼它是為了提取`exp`聲明,以便它可以確定安排下一次刷新的距離. (3認同)
總結
以上是生活随笔為你收集整理的jwt的token自动续约_JWT(JSON Web Token)自动延长到期时间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oss多线程 上传_oss-androi
- 下一篇: rockmq运维指令_RocketMQ