如何在过期后自动创建jwt令牌

时间:2017-01-28 06:33:13

标签: reactjs redux

一旦创建了jwt访问令牌,我就会在localstorage中存储它,然后我到处都在使用它。在这里,我面临问题,一旦jwt令牌过期,我无法搜索。所以我希望一旦jwt令牌到期,它应该自动创建。应该怎么做呢。感谢

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案 - 一个简单的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)
}