2017-01-28 8 views
0

jwtアクセストークンを作成したら、それをどこにでも使用しています。ここで私は問題に直面しています。一度jwtトークンが期限切れになると、私は検索できません。ですから、jwtトークンが期限切れになると自動的に作成する必要があります。それを行う方法は何でしょうか。ありがとうございますjwtトークンが期限切れになると自動的にjwtトークンを作成する方法

+0

たぶん、すべてのユーザーとの対話に有効期限を確認してください(EGアクションが派遣やルートが変更された)と有効期限が近すぎるJWTを更新している場合。このようにして、ユーザーが長い間インタラクションを持たない場合、トークンは期限切れになり、それは受け入れ可能です。 – Giladd

+0

お返事ありがとうございます。実際に私は、アクセストークンが期限切れになっているかどうかを確認していますが、何らかのイベントでアクション作成者を呼んでいます。エラーを確認するために何らかのイベントを実行する必要があることを意味します。私はjwtトークンを作成するためのアクションクリエーターを別にしています。他のアクションクリエイターの中にあるアクションクリエイターを呼び出すことはできません。私を案内してください。 –

答えて

0

ここには可能な解決策があります - 間もなく期限切れになる既存の有効期限のないトークンをリフレッシュするシンプルレフィックスミドルウェアです。

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

ありがとう私はこの方法を試してみます。 –

関連する問題