Skip to content Skip to sidebar Skip to footer

Reactjs - Silently Renew Token With Iframe

I'm trying to wrap my had around authentication processes, and implement, every 60 minutes, a silent token renew in my React app, like so: Create some watcher function, which chec

Solution 1:

I think your issue might be in your return condition in SilentTokenRenew.willTokenExpire(), specifically this: (now > token.accessToken.expirationTime). now > token.accessToken.expirationTime yields false, so your function will likely always return false unless a token doesn't exist.

The token object looks like:

{
  accessToken:TOKEN,
  expirationTime:TIME,
}

That portion of your conditional should instead be: (now > token.expirationTime).

Hopefully that helps you out.

Solution 2:

  1. In silenwRenew method, the redirectUrl needs to be retrieved from the localStorage, this is the URL what you are going to store in the redirect.html file, under the same key. So, create a key which you will use for both parts. For example:

    const redirectUrl = localStorage['silent-derirect-url-key']

    • you may need to use localStorage.getItem('silent-derirect-url-key'), but it should work with both ways.
  2. In redirect.html file, use the same key, so for setting the URL to the store, use:

    const requestKey = 'silent-derirect-url-key'

Lastly, the method extractTokenFromUrl should be simple, something like this:

extractTokenFromUrl(redirectUrl = '') {
    let accessToken = nulllet decodedAccessToken = nullconst accessTokenMatch = redirectUrl.match(/(?:[?&#/]|^)access_token=([^&]+)/)
    if (accessTokenMatch) {
      accessToken = accessTokenMatch[1]
      decodedAccessToken = JSON.parse(atob(accessToken.split('.')[1]))
    }

    let expireDurationSeconds = 3600const expireDurationSecondsMatch = redirectUrl.match(/expires_in=([^&]+)/)
    if (expireDurationSecondsMatch) {
      expireDurationSeconds = parseInt(expireDurationSecondsMatch[1], 10)
    }

    return {
      accessToken,
      decodedAccessToken,
      expireDurationSeconds,
    }
  }

Ofc you can make the code nicer, but you get the idea.

Post a Comment for "Reactjs - Silently Renew Token With Iframe"