【问题标题】:how to create jwt token automatically once it gets expired过期后如何自动创建jwt令牌
【发布时间】:2017-06-13 21:47:14
【问题描述】:

创建 jwt 访问令牌后,我将其存储在本地存储中,然后我将在任何地方使用它。在这里我面临问题,一旦 jwt 令牌过期,我就无法搜索。所以我希望一旦 jwt 令牌过期,它应该自动创建。应该怎么做。谢谢

【问题讨论】:

  • 可能会检查每次用户交互的到期时间(EG 操作已调度或路由更改),如果到期时间太近,请更新 JWT。这样,如果用户长时间没有交互,令牌就会过期,这是可以接受的。
  • 感谢您的回复。实际上,如果访问令牌是否过期,我正在检查动作创建者,但问题是我在某些事件上调用动作创建者。意味着我需要执行任何事件来检查错误。我为创建 jwt 令牌保留了单独的动作创建者。我不能在另一个动作创建者中调用一个动作创建者。请指导我。

标签: reactjs redux


【解决方案1】:

这是一个可能的解决方案 - 一个简单的 redux 中间件,它将刷新一个现有的、未过期的令牌,该令牌即将过期。

它使用jwt-decode 库并假定存在一个执行实际更新的renewToken 函数。

查看代码中的 cmets 了解更多详情。

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)
}

【讨论】:

  • 谢谢,我会尝试这种方式。
猜你喜欢
  • 2020-03-20
  • 2020-02-20
  • 2020-06-13
  • 2021-12-31
  • 2017-03-04
  • 2019-07-04
  • 2016-10-10
  • 2018-06-19
  • 2019-08-08
相关资源
最近更新 更多